package com.gzhryc.shared_device.oem.micro.api;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.lang3.time.DateUtils;

import com.gzhryc.common.ClassTools;
import com.gzhryc.common.IDTools;
import com.gzhryc.common.NumberTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.kafka.JFKafkaProducer;
import com.gzhryc.common.kafka.KafkaProducerFactory;
import com.gzhryc.common.kafka.models.KafkaMessage;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.common.redis.RedisTools;
import com.gzhryc.pay.adaptation.alipay.DefaultAlipayConfig;
import com.gzhryc.pay.adaptation.alipay.enums.EAliPayNormalTradeState;
import com.gzhryc.pay.adaptation.alipay.enums.EAlipayAdvanceOrderState;
import com.gzhryc.pay.adaptation.alipay.msg.advance_pay.AlipayAdvancePayConfirmNotify;
import com.gzhryc.pay.adaptation.alipay.msg.normal.AlipayNormalPayNotify;
import com.gzhryc.pay.adaptation.weixin.DefaultWXPayConfig;
import com.gzhryc.pay.adaptation.weixin.enums.EWXPayAdvanceOrderState;
import com.gzhryc.pay.adaptation.weixin.enums.EWXPayAdvanceServerState;
import com.gzhryc.pay.adaptation.weixin.enums.EWXPayNormalPayState;
import com.gzhryc.pay.adaptation.weixin.msg.advance_pay.WXPayAdvancePayConfirmNotify;
import com.gzhryc.pay.adaptation.weixin.msg.advance_pay.WXPayAdvancePayFinishNotify;
import com.gzhryc.pay.adaptation.weixin.msg.normal.WXPayNormalPayNotify;
import com.gzhryc.pay.enums.TradeType;
import com.gzhryc.shared_device.base.enums.EDiscountType;
import com.gzhryc.shared_device.base.enums.ELogState;
import com.gzhryc.shared_device.base.enums.EPayState;
import com.gzhryc.shared_device.base.enums.EPayType;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.base.models.OrderLogContent;
import com.gzhryc.shared_device.bxscn.code.dao.db.BXSCNBatteryTypeDayCost;
import com.gzhryc.shared_device.bxscn.code.dao.db.BXSCNFeeTemplate;
import com.gzhryc.shared_device.bxscn.code.dao.db.BXSCNOrder;
import com.gzhryc.shared_device.bxscn.code.dao.db.BXSCNShopFeeTemplateItem;
import com.gzhryc.shared_device.bxscn.code.dao.db.BXSCNShopOrder;
import com.gzhryc.shared_device.bxscn.code.dao.db.PortableEnergyBatteryType;
import com.gzhryc.shared_device.bxscn.code.dao.db.PortableEnergyCabinet;
import com.gzhryc.shared_device.bxscn.code.dao.enums.BXSCNShopFeeTemplateItemEnum;
import com.gzhryc.shared_device.bxscn.code.dao.enums.BXSCNShopOrderEnum;
import com.gzhryc.shared_device.bxscn.code.dao.enums.EBXSCNCostMode;
import com.gzhryc.shared_device.bxscn.code.dao.models.BXSCNBatteryTypeDayMoneyContent;
import com.gzhryc.shared_device.bxscn.code.services.BXSCNBatteryTypeDayCostService;
import com.gzhryc.shared_device.bxscn.code.services.BXSCNOrderService;
import com.gzhryc.shared_device.bxscn.code.services.BXSCNShopFeeTemplateService;
import com.gzhryc.shared_device.bxscn.code.services.BXSCNShopOrderService;
import com.gzhryc.shared_device.bxscn.code.services.PortableEnergyBatteryTypeService;
import com.gzhryc.shared_device.bxscn.core.IBXSCNNetworkService;
import com.gzhryc.shared_device.cdb.code.dao.db.BatteryCabinet;
import com.gzhryc.shared_device.cdb.code.dao.db.CDBFeeTemplate;
import com.gzhryc.shared_device.cdb.code.dao.db.CDBOrder;
import com.gzhryc.shared_device.cdb.code.dao.enums.CDBOrderEnum;
import com.gzhryc.shared_device.cdb.code.dao.enums.ECDBCostMode;
import com.gzhryc.shared_device.cdb.code.services.CDBOrderService;
import com.gzhryc.shared_device.cdb.core.ICDBNetworkService;
import com.gzhryc.shared_device.cdcz.code.CDCZCostConfig;
import com.gzhryc.shared_device.cdcz.code.dao.db.CDCZFeeTemplate;
import com.gzhryc.shared_device.cdcz.code.dao.db.CDCZOrder;
import com.gzhryc.shared_device.cdcz.code.dao.db.ChargeSocketSlot;
import com.gzhryc.shared_device.cdcz.code.services.CDCZOrderService;
import com.gzhryc.shared_device.cdcz.core.ICDCZNetworkService;
import com.gzhryc.shared_device.cdcz.core.enums.ECDCZCostMode;
import com.gzhryc.shared_device.common.BusyThreadPool;
import com.gzhryc.shared_device.common.device.dao.db.Device;
import com.gzhryc.shared_device.common.payment.dao.db.AlipayAbnormalPayOrder;
import com.gzhryc.shared_device.common.payment.dao.db.AlipayOrder;
import com.gzhryc.shared_device.common.payment.dao.db.WXPayAbnormalPayOrder;
import com.gzhryc.shared_device.common.payment.dao.db.WXPayOrder;
import com.gzhryc.shared_device.common.payment.dao.enums.AlipayAbnormalPayOrderEnum;
import com.gzhryc.shared_device.common.payment.dao.enums.AlipayConfigEnum;
import com.gzhryc.shared_device.common.payment.dao.enums.WXPayAbnormalPayOrderEnum;
import com.gzhryc.shared_device.common.payment.dao.enums.WXPayConfigEnum;
import com.gzhryc.shared_device.common.payment.services.AlipayAbnormalPayOrderService;
import com.gzhryc.shared_device.common.payment.services.AlipayOrderService;
import com.gzhryc.shared_device.common.payment.services.WXPayAbnormalPayOrderService;
import com.gzhryc.shared_device.common.payment.services.WXPayOrderService;
import com.gzhryc.shared_device.oem.code.ConfigUtils;
import com.gzhryc.shared_device.oem.code.HttpNetworkServiceUtils;
import com.gzhryc.shared_device.oem.code.KafkaEventConstants;
import com.gzhryc.shared_device.oem.code.RedisDBConstants;
import com.gzhryc.shared_device.oem.code.business.EBusinessType;
import com.gzhryc.shared_device.oem.code.member.EMemberBusinessType;
import com.gzhryc.shared_device.oem.code.member.LoginMember;
import com.gzhryc.shared_device.oem.code.member.dao.db.MemberRechargeOrder;
import com.gzhryc.shared_device.oem.code.member.event.MemberRechargeFinishEvent;
import com.gzhryc.shared_device.oem.code.member.services.MemberBusinessOrderService;
import com.gzhryc.shared_device.oem.code.member.services.MemberRechargeOrderService;
import com.gzhryc.shared_device.oem.code.member.services.MemberWalletService;
import com.gzhryc.shared_device.oem.code.order.CacheOrderCollect;
import com.gzhryc.shared_device.oem.code.order.OrderTradeNoPrefix;
import com.gzhryc.shared_device.oem.code.order.RedisCacheManager;
import com.gzhryc.shared_device.oem.code.order.event.OrderCreateEvent;
import com.gzhryc.shared_device.oem.code.order.event.OrderFinishEvent;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlaceBusinessConfig;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlacePhysicalStore;
import com.gzhryc.shared_device.oem.code.place.services.PlaceBusinessConfigService;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreService;
import com.gzhryc.shared_device.pcl.code.dao.db.ChargingCable;
import com.gzhryc.shared_device.pcl.code.dao.db.PCLFeeTemplate;
import com.gzhryc.shared_device.pcl.code.dao.db.PCLOrder;
import com.gzhryc.shared_device.pcl.code.dao.enums.EPCLCostMode;
import com.gzhryc.shared_device.pcl.code.dao.enums.PCLOrderEnum;
import com.gzhryc.shared_device.pcl.code.dao.models.SetMealContent;
import com.gzhryc.shared_device.pcl.code.services.PCLOrderService;

public class OrderCollectManager {

    static Logger log = Logger.getLogger(OrderCollectManager.class);

    static Long times = 180L; //3分钟
    static AtomicInteger counter = new AtomicInteger(0);

    public static CacheOrderCollect buildMemberRechargeOrderCollect(LoginMember loginMember, Double money, DefaultWXPayConfig payConfig,
                                                                    OperateInfo operateInfo) throws LogicException {
        String tradeNo = OrderTradeNoPrefix.MEMBER_RECHARGE_ORDER + IDTools.getTimestampSecondID() + String.format("%03d", counter.getAndIncrement());
        Date createDate = new Date();
        Integer rechargeMoney = NumberTools.changeMoney(money);

        CacheOrderCollect orderCollect = new CacheOrderCollect();
        WXPayOrder payOrder = new WXPayOrder();
        payOrder.setTradeNo(tradeNo);
        payOrder.setTitle("会员充值");
        payOrder.setNote("会员[" + loginMember.getNickname() + "]在线充值" + money + "元");
        payOrder.setBusinessType(EBusinessType.RECHARGE.index());
        payOrder.setBusinessTypeName(EBusinessType.RECHARGE.note());
        payOrder.setBusinessTradeNo(tradeNo);
        payOrder.setAppType(WXPayConfigEnum.AppType.wxxcx.index());
        payOrder.setAppId(payConfig.getAppId());
        payOrder.setPayerId(loginMember.getOpenId());
        payOrder.setBusinessAccount(payConfig.getMchId());
        payOrder.setTradeType(TradeType.Normal.name());
        payOrder.setPayMoney(rechargeMoney);
        payOrder.setClientIP(payConfig.getServerIp());
        payOrder.setNotifyUrl(payConfig.getPayNotifyUrl());
        payOrder.setCreateDate(createDate);

        orderCollect.setPayOrder(payOrder);

        MemberRechargeOrder rechargeOrder = new MemberRechargeOrder();
        rechargeOrder.setTradeNo(tradeNo);
        rechargeOrder.setMemberId(loginMember.getId());
        rechargeOrder.setNickname(loginMember.getNickname());
        rechargeOrder.setPhone(loginMember.getPhone());
        rechargeOrder.setMoney(rechargeMoney);
        rechargeOrder.setPayType(EPayType.WXPay.index());
        rechargeOrder.setPayTradeNo(tradeNo);
        rechargeOrder.setCreateDate(createDate);

        orderCollect.setMemberRechargeOrder(rechargeOrder);

        OrderLogContent logContent = new OrderLogContent();
        OrderLogContent.LogItem logItem = new OrderLogContent.LogItem();
        logItem.setCreateDate(createDate);
        if (StringTools.isNotBlank(operateInfo.getOperateNote())) {
            logItem.setContent("创建充值订单，" + operateInfo.getOperateNote());
        } else {
            logItem.setContent("创建充值订单");
        }
        logItem.setState(ELogState.Success.index());
        logItem.setProgramTypeName(operateInfo.getProgramTypeName());
        logItem.setOperatorType(operateInfo.getOperatorType());
        logItem.setOperatorTypeName(operateInfo.getOperatorTypeName());
        logItem.setOperator(operateInfo.getOperator());
        logContent.getItems().add(logItem);

        orderCollect.setLogContent(logContent);

        if (!RedisTools.get().exists(RedisDBConstants.ORDER_CACHE_DB, tradeNo)) {
            if (RedisTools.get().set(RedisDBConstants.ORDER_CACHE_DB, tradeNo, JsonTools.toJson(orderCollect), times)) {
                return orderCollect;
            }
        } else {
            log.error("创建会员充值订单时，订单号冲突");
            throw new LogicException("系统繁忙，请稍后再试");
        }
        return null;
    }

    public static CacheOrderCollect buildMemberRechargeOrderCollect(LoginMember loginMember, Double money, DefaultAlipayConfig payConfig,
            OperateInfo operateInfo) throws LogicException {
		String tradeNo = OrderTradeNoPrefix.MEMBER_RECHARGE_ORDER + IDTools.getTimestampSecondID() + String.format("%03d", counter.getAndIncrement());
		Date createDate = new Date();
		Integer rechargeMoney = NumberTools.changeMoney(money);
		
		CacheOrderCollect orderCollect = new CacheOrderCollect();
		AlipayOrder payOrder = new AlipayOrder();
        payOrder.setTradeNo(tradeNo);
    	payOrder.setTitle("会员充值");
        payOrder.setNote("会员[" + loginMember.getNickname() + "]在线充值" + money + "元");
        payOrder.setBusinessType(EBusinessType.RECHARGE.index());
        payOrder.setBusinessTypeName(EBusinessType.RECHARGE.note());
        payOrder.setBusinessTradeNo(tradeNo);
        payOrder.setAppType(AlipayConfigEnum.AppType.alixcx.index());
        payOrder.setAppId(payConfig.getAppId());
        payOrder.setPayerId(loginMember.getOpenId());
        payOrder.setBusinessAccount(payConfig.getPid());
        payOrder.setTradeType(TradeType.Normal.name());
        payOrder.setPayMoney(rechargeMoney);
        payOrder.setNotifyUrl(payConfig.getPayNotifyUrl());
        payOrder.setCreateDate(createDate);
		
		orderCollect.setAlipayOrder(payOrder);
		
		MemberRechargeOrder rechargeOrder = new MemberRechargeOrder();
		rechargeOrder.setTradeNo(tradeNo);
		rechargeOrder.setMemberId(loginMember.getId());
		rechargeOrder.setNickname(loginMember.getNickname());
		rechargeOrder.setPhone(loginMember.getPhone());
		rechargeOrder.setMoney(rechargeMoney);
		rechargeOrder.setPayType(EPayType.Alipay.index());
		rechargeOrder.setPayTradeNo(tradeNo);
		rechargeOrder.setCreateDate(createDate);
		
		orderCollect.setMemberRechargeOrder(rechargeOrder);
		
		OrderLogContent logContent = new OrderLogContent();
		OrderLogContent.LogItem logItem = new OrderLogContent.LogItem();
		logItem.setCreateDate(createDate);
		if (StringTools.isNotBlank(operateInfo.getOperateNote())) {
			logItem.setContent("创建充值订单，" + operateInfo.getOperateNote());
		} else {
			logItem.setContent("创建充值订单");
		}
		logItem.setState(ELogState.Success.index());
		logItem.setProgramTypeName(operateInfo.getProgramTypeName());
		logItem.setOperatorType(operateInfo.getOperatorType());
		logItem.setOperatorTypeName(operateInfo.getOperatorTypeName());
		logItem.setOperator(operateInfo.getOperator());
		logContent.getItems().add(logItem);
		
		orderCollect.setLogContent(logContent);
		
		if (!RedisTools.get().exists(RedisDBConstants.ORDER_CACHE_DB, tradeNo)) {
			if (RedisTools.get().set(RedisDBConstants.ORDER_CACHE_DB, tradeNo, JsonTools.toJson(orderCollect), times)) {
				return orderCollect;
			}
		} else {
			log.error("创建会员充值订单时，订单号冲突");
			throw new LogicException("系统繁忙，请稍后再试");
		}
		return null;
    }
    
    public static CacheOrderCollect buildCDCZCacheOrderCollect(LoginMember loginMember, Device device, ChargeSocketSlot deviceSlot,
                                                               CDCZFeeTemplate freightBasis, Integer timesMinute, OperateInfo operateInfo) throws LogicException {
        PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(device.getPlaceId());
        if(physicalStore == null) {
            throw new LogicException("未找到设备部署的网点信息");
        }

        String tradeNo = OrderTradeNoPrefix.CDCZ_DEVICE_ORDER + IDTools.getTimestampSecondID() + String.format("%03d", counter.getAndIncrement());
        Date createDate = new Date();
        CDCZCostConfig config = ConfigUtils.getCDCZCostConfig();
        Integer costMode = ECDCZCostMode.TimeSetMeal.index();

        if (timesMinute == null || timesMinute <= 0) {
            timesMinute = config.getMaxTimesMinute(); //默认24小时
            costMode = ECDCZCostMode.FillSetMeal.index();
        }

        CacheOrderCollect orderCollect = new CacheOrderCollect();
        CDCZOrder deviceOrder = new CDCZOrder();
        deviceOrder.setTradeNo(tradeNo);
        deviceOrder.setDeviceTypeId(device.getDeviceTypeId());
        deviceOrder.setDeviceTypeName(device.getDeviceTypeName());
        deviceOrder.setIotId(deviceSlot.getIotNodeId());
        deviceOrder.setChargeSocketSn(device.getDeviceSn());
        deviceOrder.setSlotNum(deviceSlot.getSlotNum());
        deviceOrder.setBindNote(device.getBindNote());

        deviceOrder.setPlaceId(device.getPlaceId());
        deviceOrder.setPlaceName(device.getPlaceName());
        deviceOrder.setProvince(device.getProvince());
        deviceOrder.setCity(device.getCity());
        deviceOrder.setCityArea(device.getCityArea());
        deviceOrder.setAreaCode(device.getAreaCode());
        deviceOrder.setAddress(physicalStore.getAddress());
        deviceOrder.setLatitude(physicalStore.getLatitude());
        deviceOrder.setLongitude(physicalStore.getLongitude());
        deviceOrder.setAgentId(physicalStore.getUserId());

        deviceOrder.setMemberId(loginMember.getId());
        deviceOrder.setMemberName(loginMember.getNickname());
        deviceOrder.setMemberPhone(loginMember.getPhone());

        deviceOrder.setMaxUseChargeElectricity(config.getMaxChargeElectricity());
        deviceOrder.setMaxUseTimes(timesMinute);
        deviceOrder.setCostMode(costMode);
        deviceOrder.setPayType(EPayType.EWallet.index());
        deviceOrder.setPayTradeNo(tradeNo);
        deviceOrder.setCreateDate(createDate);

        OrderLogContent logContent = new OrderLogContent();
        OrderLogContent.LogItem logItem = new OrderLogContent.LogItem();
        logItem.setProgramType(operateInfo.getProgramType());
        logItem.setProgramTypeName(operateInfo.getProgramTypeName());
        logItem.setOperatorType(operateInfo.getOperatorType());
        logItem.setOperatorTypeName(operateInfo.getOperatorTypeName());
        logItem.setOperator(operateInfo.getOperator());
        logItem.setContent("创建订单");
        logItem.setCreateDate(createDate);
        logItem.setState(ELogState.Success.index());
        logContent.getItems().add(logItem);

        orderCollect.setLogContent(logContent);

        //会员信息
        orderCollect.setDevice(device);
        if (MemberWalletService.self().hasMoney(loginMember.getId(), freightBasis.getMinWalletMoney())) {
            deviceOrder.setPayState(EPayState.Success.index());
            deviceOrder.setPayDate(new Date());

            ICDCZNetworkService networkService = HttpNetworkServiceUtils.getCDCZNetworkService(deviceOrder.getIotId());
            if (CDCZOrderService.self(deviceOrder.getCreateDate()).paySuccess(deviceOrder, logContent, networkService, operateInfo)) {
                //添加会员订单
                if(MemberBusinessOrderService.self(deviceOrder.getCreateDate()).create(deviceOrder) == null){
                    log.error("充电插座订单创建会员订单失败，订单号：{{0}}",deviceOrder.getTradeNo());
                }
                //触发业务订单创建事件
                JFKafkaProducer producer = KafkaProducerFactory.self().getProducer();
                if (producer != null) {
                    OrderCreateEvent event = new OrderCreateEvent(EBusinessType.CDCZ.name(), deviceOrder.getTradeNo(),deviceOrder.getCreateDate());
                    KafkaMessage kafkaMessage = new KafkaMessage(KafkaEventConstants.TOPIC_Order,
                            KafkaEventConstants.KEY_OrderCreate, JsonTools.toJson(event));
                    producer.send(kafkaMessage);
                } else {
                    log.error("消息队列未初始化");
                }
                orderCollect.setCdczOrder(deviceOrder);
                return orderCollect;
            } else {
                log.error("充电插座订单支付完成处理失败，订单：{{0:json}}", deviceOrder);
            }
        } else {
            log.error("创建充电插座订单时，会员余额不足");
            throw new LogicException("余额不足");
        }
        return null;
    }

    public static CacheOrderCollect buildCDBCacheAdvanceOrderCollect(LoginMember loginMember, Device device, BatteryCabinet batteryCabinet, CDBFeeTemplate freightBasis
            , DefaultWXPayConfig payConfig, OperateInfo operateInfo) throws LogicException {
        PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(device.getPlaceId());
        if(physicalStore == null) {
            throw new LogicException("未找到设备部署的网点信息");
        }
        String tradeNo = OrderTradeNoPrefix.CDB_DEVICE_ORDER + IDTools.getTimestampSecondID() + String.format("%03d", counter.getAndIncrement());
        Date createDate = new Date();
        Integer depositMoney = freightBasis.getDepositMoney();

        CacheOrderCollect orderCollect = new CacheOrderCollect();
        WXPayOrder payOrder = new WXPayOrder();
        payOrder.setTradeNo(tradeNo);
        payOrder.setTitle("充电宝租借");
        payOrder.setNote("会员[" + loginMember.getNickname() + "]充电宝租借");
        payOrder.setBusinessType(EBusinessType.CDB.index());
        payOrder.setBusinessTypeName(EBusinessType.CDB.note());
        payOrder.setBusinessTradeNo(tradeNo);
        payOrder.setAppType(WXPayConfigEnum.AppType.wxxcx.index());
        payOrder.setAppId(payConfig.getAppId());
        payOrder.setPayerId(loginMember.getOpenId());
        payOrder.setBusinessAccount(payConfig.getMchId());
        payOrder.setTradeType(TradeType.PreAuthPay.name());
        payOrder.setPayMoney(depositMoney);
        payOrder.setClientIP(payConfig.getServerIp());
        payOrder.setNotifyUrl(payConfig.getPreAuthNotifyUrl());		//免押回调路径
        payOrder.setCreateDate(createDate);

        orderCollect.setPayOrder(payOrder);

        CDBOrder deviceOrder = new CDBOrder();
        deviceOrder.setTradeNo(tradeNo);

        deviceOrder.setLeaseDeviceTypeId(device.getDeviceTypeId());
        deviceOrder.setLeaseDeviceTypeName(device.getDeviceTypeName());
        deviceOrder.setLeaseChargingCabinetSn(device.getDeviceSn());
        deviceOrder.setLeaseBindNote(device.getBindNote());
        deviceOrder.setLeaseIotId(batteryCabinet.getIotNodeId());
        deviceOrder.setLeasePlaceId(device.getPlaceId());
        deviceOrder.setLeasePlaceName(device.getPlaceName());
        deviceOrder.setLeaseProvince(device.getProvince());
        deviceOrder.setLeaseCity(device.getCity());
        deviceOrder.setLeaseCityArea(device.getCityArea());
        deviceOrder.setLeaseAreaCode(device.getAreaCode());
        deviceOrder.setLeaseAddress(physicalStore.getAddress());
        deviceOrder.setLeaseLatitude(physicalStore.getLatitude());
        deviceOrder.setLeaseLongitude(physicalStore.getLongitude());
        deviceOrder.setLeaseAgentId(physicalStore.getUserId());

        deviceOrder.setMemberId(loginMember.getId());
        deviceOrder.setMemberName(loginMember.getNickname());
        deviceOrder.setMemberPhone(loginMember.getPhone());

        deviceOrder.setCostMode(ECDBCostMode.ExemptionDeposit.index());
        deviceOrder.setDepositMoney(freightBasis.getDepositMoney());
        deviceOrder.setFreeTimes(freightBasis.getFreeTimes());
        deviceOrder.setPayIntervalMoney(freightBasis.getPayIntervalMoney());
        deviceOrder.setDayMaxMoney(freightBasis.getDayMaxMoney());

        deviceOrder.setPayType(EPayType.WXPay.index());
        deviceOrder.setPayTradeNo(tradeNo);
        deviceOrder.setCreateDate(createDate);

        orderCollect.setCdbOrder(deviceOrder);

        OrderLogContent logContent = new OrderLogContent();
        OrderLogContent.LogItem logItem = new OrderLogContent.LogItem();
        logItem.setCreateDate(createDate);
        if (StringTools.isNotBlank(operateInfo.getOperateNote())) {
            logItem.setContent("创建租借订单，" + operateInfo.getOperateNote());
        } else {
            logItem.setContent("创建租借订单");
        }
        logItem.setState(ELogState.Success.index());
        logItem.setProgramTypeName(operateInfo.getProgramTypeName());
        logItem.setOperatorType(operateInfo.getOperatorType());
        logItem.setOperatorTypeName(operateInfo.getOperatorTypeName());
        logItem.setOperator(operateInfo.getOperator());
        logContent.getItems().add(logItem);

        orderCollect.setLogContent(logContent);

        try {
            if (!RedisTools.get().exists(RedisDBConstants.ORDER_CACHE_DB, tradeNo)) {
                if (RedisTools.get().set(RedisDBConstants.ORDER_CACHE_DB, tradeNo, JsonTools.toJson(orderCollect), times)) {
                    return orderCollect;
                }
            } else {
                log.error("创建充电宝租借订单时，订单号冲突，订单号：{{0}}",tradeNo);
                throw new LogicException("系统繁忙，请稍后再试");
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return null;
    }
    
    public static CacheOrderCollect buildCDBCacheOrderCollect(LoginMember loginMember, Device device, BatteryCabinet batteryCabinet, CDBFeeTemplate freightBasis
            , DefaultWXPayConfig payConfig, OperateInfo operateInfo) throws LogicException {
        PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(device.getPlaceId());
        if(physicalStore == null) {
            throw new LogicException("未找到设备部署的网点信息");
        }
        String tradeNo = OrderTradeNoPrefix.CDB_DEVICE_ORDER + IDTools.getTimestampSecondID() + String.format("%03d", counter.getAndIncrement());
        Date createDate = new Date();
        Integer depositMoney = freightBasis.getDepositMoney();

        CacheOrderCollect orderCollect = new CacheOrderCollect();
        WXPayOrder payOrder = new WXPayOrder();
        payOrder.setTradeNo(tradeNo);
        payOrder.setTitle("充电宝租借");
        payOrder.setNote("会员[" + loginMember.getNickname() + "]充电宝租借");
        payOrder.setBusinessType(EBusinessType.CDB.index());
        payOrder.setBusinessTypeName(EBusinessType.CDB.note());
        payOrder.setBusinessTradeNo(tradeNo);
        payOrder.setAppType(WXPayConfigEnum.AppType.wxxcx.index());
        payOrder.setAppId(payConfig.getAppId());
        payOrder.setPayerId(loginMember.getOpenId());
        payOrder.setBusinessAccount(payConfig.getMchId());
        payOrder.setTradeType(TradeType.Normal.name());
        payOrder.setPayMoney(depositMoney);
        payOrder.setClientIP(payConfig.getServerIp());
        payOrder.setNotifyUrl(payConfig.getPayNotifyUrl());
        payOrder.setCreateDate(createDate);

        orderCollect.setPayOrder(payOrder);

        CDBOrder deviceOrder = new CDBOrder();
        deviceOrder.setTradeNo(tradeNo);

        deviceOrder.setLeaseDeviceTypeId(device.getDeviceTypeId());
        deviceOrder.setLeaseDeviceTypeName(device.getDeviceTypeName());
        deviceOrder.setLeaseChargingCabinetSn(device.getDeviceSn());
        deviceOrder.setLeaseBindNote(device.getBindNote());
        deviceOrder.setLeaseIotId(batteryCabinet.getIotNodeId());
        deviceOrder.setLeasePlaceId(device.getPlaceId());
        deviceOrder.setLeasePlaceName(device.getPlaceName());
        deviceOrder.setLeaseProvince(device.getProvince());
        deviceOrder.setLeaseCity(device.getCity());
        deviceOrder.setLeaseCityArea(device.getCityArea());
        deviceOrder.setLeaseAreaCode(device.getAreaCode());
        deviceOrder.setLeaseAddress(physicalStore.getAddress());
        deviceOrder.setLeaseLatitude(physicalStore.getLatitude());
        deviceOrder.setLeaseLongitude(physicalStore.getLongitude());
        deviceOrder.setLeaseAgentId(physicalStore.getUserId());

        deviceOrder.setMemberId(loginMember.getId());
        deviceOrder.setMemberName(loginMember.getNickname());
        deviceOrder.setMemberPhone(loginMember.getPhone());

        deviceOrder.setCostMode(ECDBCostMode.Deposit.index());
        deviceOrder.setDepositMoney(freightBasis.getDepositMoney());
        deviceOrder.setFreeTimes(freightBasis.getFreeTimes());
        deviceOrder.setPayIntervalMoney(freightBasis.getPayIntervalMoney());
        deviceOrder.setDayMaxMoney(freightBasis.getDayMaxMoney());

        deviceOrder.setPayType(EPayType.WXPay.index());
        deviceOrder.setPayTradeNo(tradeNo);
        deviceOrder.setCreateDate(createDate);

        orderCollect.setCdbOrder(deviceOrder);

        OrderLogContent logContent = new OrderLogContent();
        OrderLogContent.LogItem logItem = new OrderLogContent.LogItem();
        logItem.setCreateDate(createDate);
        if (StringTools.isNotBlank(operateInfo.getOperateNote())) {
            logItem.setContent("创建租借订单，" + operateInfo.getOperateNote());
        } else {
            logItem.setContent("创建租借订单");
        }
        logItem.setState(ELogState.Success.index());
        logItem.setProgramTypeName(operateInfo.getProgramTypeName());
        logItem.setOperatorType(operateInfo.getOperatorType());
        logItem.setOperatorTypeName(operateInfo.getOperatorTypeName());
        logItem.setOperator(operateInfo.getOperator());
        logContent.getItems().add(logItem);

        orderCollect.setLogContent(logContent);

        try {
            if (!RedisTools.get().exists(RedisDBConstants.ORDER_CACHE_DB, tradeNo)) {
                if (RedisTools.get().set(RedisDBConstants.ORDER_CACHE_DB, tradeNo, JsonTools.toJson(orderCollect), times)) {
                    return orderCollect;
                }
            } else {
                log.error("创建充电宝租借订单时，订单号冲突，订单号：{{0}}",tradeNo);
                throw new LogicException("系统繁忙，请稍后再试");
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return null;
    }
    
    public static CacheOrderCollect buildCDBCacheOrderCollect(LoginMember loginMember, Device device, BatteryCabinet batteryCabinet, CDBFeeTemplate freightBasis
            , DefaultAlipayConfig payConfig, OperateInfo operateInfo) throws LogicException {
        PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(device.getPlaceId());
        if(physicalStore == null) {
            throw new LogicException("未找到设备部署的网点信息");
        }
        String tradeNo = OrderTradeNoPrefix.CDB_DEVICE_ORDER + IDTools.getTimestampSecondID() + String.format("%03d", counter.getAndIncrement());
        Date createDate = new Date();
        Integer depositMoney = freightBasis.getDepositMoney();

        CacheOrderCollect orderCollect = new CacheOrderCollect();
        AlipayOrder payOrder = new AlipayOrder();
        payOrder.setTradeNo(tradeNo);
        payOrder.setTitle("充电宝租借");
        payOrder.setNote("会员[" + loginMember.getNickname() + "]充电宝租借");
        payOrder.setBusinessType(EBusinessType.CDB.index());
        payOrder.setBusinessTypeName(EBusinessType.CDB.note());
        payOrder.setBusinessTradeNo(tradeNo);
        payOrder.setAppType(AlipayConfigEnum.AppType.alixcx.index());
        payOrder.setAppId(payConfig.getAppId());
        payOrder.setPayerId(loginMember.getOpenId());
        payOrder.setBusinessAccount(payConfig.getPid());
        payOrder.setTradeType(TradeType.Normal.name());
        payOrder.setPayMoney(depositMoney);
        payOrder.setNotifyUrl(payConfig.getPayNotifyUrl());
        payOrder.setCreateDate(createDate);
        
        orderCollect.setAlipayOrder(payOrder);

        CDBOrder deviceOrder = new CDBOrder();
        deviceOrder.setTradeNo(tradeNo);

        deviceOrder.setLeaseDeviceTypeId(device.getDeviceTypeId());
        deviceOrder.setLeaseDeviceTypeName(device.getDeviceTypeName());
        deviceOrder.setLeaseChargingCabinetSn(device.getDeviceSn());
        deviceOrder.setLeaseBindNote(device.getBindNote());
        deviceOrder.setLeaseIotId(batteryCabinet.getIotNodeId());
        deviceOrder.setLeasePlaceId(device.getPlaceId());
        deviceOrder.setLeasePlaceName(device.getPlaceName());
        deviceOrder.setLeaseProvince(device.getProvince());
        deviceOrder.setLeaseCity(device.getCity());
        deviceOrder.setLeaseCityArea(device.getCityArea());
        deviceOrder.setLeaseAreaCode(device.getAreaCode());
        deviceOrder.setLeaseAddress(physicalStore.getAddress());
        deviceOrder.setLeaseLatitude(physicalStore.getLatitude());
        deviceOrder.setLeaseLongitude(physicalStore.getLongitude());
        deviceOrder.setLeaseAgentId(physicalStore.getUserId());

        deviceOrder.setMemberId(loginMember.getId());
        deviceOrder.setMemberName(loginMember.getNickname());
        deviceOrder.setMemberPhone(loginMember.getPhone());

        deviceOrder.setCostMode(ECDBCostMode.Deposit.index());
        deviceOrder.setDepositMoney(freightBasis.getDepositMoney());
        deviceOrder.setFreeTimes(freightBasis.getFreeTimes());
        deviceOrder.setPayIntervalMoney(freightBasis.getPayIntervalMoney());
        deviceOrder.setDayMaxMoney(freightBasis.getDayMaxMoney());

        deviceOrder.setPayType(EPayType.Alipay.index());
        deviceOrder.setPayTradeNo(tradeNo);
        deviceOrder.setCreateDate(createDate);

        orderCollect.setCdbOrder(deviceOrder);

        OrderLogContent logContent = new OrderLogContent();
        OrderLogContent.LogItem logItem = new OrderLogContent.LogItem();
        logItem.setCreateDate(createDate);
        if (StringTools.isNotBlank(operateInfo.getOperateNote())) {
            logItem.setContent("创建租借订单，" + operateInfo.getOperateNote());
        } else {
            logItem.setContent("创建租借订单");
        }
        logItem.setState(ELogState.Success.index());
        logItem.setProgramTypeName(operateInfo.getProgramTypeName());
        logItem.setOperatorType(operateInfo.getOperatorType());
        logItem.setOperatorTypeName(operateInfo.getOperatorTypeName());
        logItem.setOperator(operateInfo.getOperator());
        logContent.getItems().add(logItem);

        orderCollect.setLogContent(logContent);

        try {
            if (!RedisTools.get().exists(RedisDBConstants.ORDER_CACHE_DB, tradeNo)) {
                if (RedisTools.get().set(RedisDBConstants.ORDER_CACHE_DB, tradeNo, JsonTools.toJson(orderCollect), times)) {
                    return orderCollect;
                }
            } else {
                log.error("创建充电宝租借订单时，订单号冲突，订单号：{{0}}",tradeNo);
                throw new LogicException("系统繁忙，请稍后再试");
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return null;
    }
    
    public static CacheOrderCollect buildPCLCacheOrderCollect(LoginMember loginMember, Device device, ChargingCable chargingCable, PCLFeeTemplate freightBasis
            , SetMealContent.Item setMealItem, DefaultWXPayConfig payConfig, OperateInfo operateInfo) throws LogicException {
        PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(device.getPlaceId());
        if(physicalStore == null) {
            throw new LogicException("未找到设备部署的网点信息");
        }
        String tradeNo = OrderTradeNoPrefix.PCL_DEVICE_ORDER + IDTools.getTimestampSecondID() + String.format("%03d", counter.getAndIncrement());
        Date createDate = new Date();

        CacheOrderCollect orderCollect = new CacheOrderCollect();
        WXPayOrder payOrder = new WXPayOrder();
        payOrder.setTradeNo(tradeNo);
        payOrder.setTitle("便捷线充租借");
        payOrder.setNote("会员[" + loginMember.getNickname() + "]便捷线充租借");
        payOrder.setBusinessType(EBusinessType.PCL.index());
        payOrder.setBusinessTypeName(EBusinessType.PCL.note());
        payOrder.setBusinessTradeNo(tradeNo);
        payOrder.setAppType(WXPayConfigEnum.AppType.wxxcx.index());
        payOrder.setAppId(payConfig.getAppId());
        payOrder.setPayerId(loginMember.getOpenId());
        payOrder.setBusinessAccount(payConfig.getMchId());
        payOrder.setTradeType(TradeType.Normal.name());
        payOrder.setPayMoney(setMealItem.getMoney());
        payOrder.setClientIP(payConfig.getServerIp());
        payOrder.setNotifyUrl(payConfig.getPayNotifyUrl());
        payOrder.setCreateDate(createDate);

        orderCollect.setPayOrder(payOrder);

        PCLOrder deviceOrder = new PCLOrder();
        deviceOrder.setTradeNo(tradeNo);

        deviceOrder.setDeviceTypeId(device.getDeviceTypeId());
        deviceOrder.setDeviceTypeName(device.getDeviceTypeName());
        deviceOrder.setChargingCableSn(device.getDeviceSn());
        deviceOrder.setPlaceId(device.getPlaceId());
        deviceOrder.setPlaceName(device.getPlaceName());
        deviceOrder.setProvince(device.getProvince());
        deviceOrder.setCity(device.getCity());
        deviceOrder.setCityArea(device.getCityArea());
        deviceOrder.setAreaCode(device.getAreaCode());
        deviceOrder.setAddress(physicalStore.getAddress());
        deviceOrder.setLatitude(physicalStore.getLatitude());
        deviceOrder.setLongitude(physicalStore.getLongitude());
        deviceOrder.setAgentId(physicalStore.getUserId());

        deviceOrder.setMemberId(loginMember.getId());
        deviceOrder.setMemberName(loginMember.getNickname());
        deviceOrder.setMemberPhone(loginMember.getPhone());

        deviceOrder.setCostMode(EPCLCostMode.SetMeal.index());
        deviceOrder.setSetMealId(setMealItem.getId());
        deviceOrder.setSetMealName(setMealItem.getName());
        deviceOrder.setUseTimes(setMealItem.getTimes());

        deviceOrder.setPayType(EPayType.WXPay.index());
        deviceOrder.setPayTradeNo(tradeNo);
        deviceOrder.setCreateDate(createDate);

        orderCollect.setPclOrder(deviceOrder);

        OrderLogContent logContent = new OrderLogContent();
        OrderLogContent.LogItem logItem = new OrderLogContent.LogItem();
        logItem.setCreateDate(createDate);
        if (StringTools.isNotBlank(operateInfo.getOperateNote())) {
            logItem.setContent("创建租借订单，" + operateInfo.getOperateNote());
        } else {
            logItem.setContent("创建租借订单");
        }
        logItem.setState(ELogState.Success.index());
        logItem.setProgramTypeName(operateInfo.getProgramTypeName());
        logItem.setOperatorType(operateInfo.getOperatorType());
        logItem.setOperatorTypeName(operateInfo.getOperatorTypeName());
        logItem.setOperator(operateInfo.getOperator());
        logContent.getItems().add(logItem);

        orderCollect.setLogContent(logContent);

        try {
            if (!RedisTools.get().exists(RedisDBConstants.ORDER_CACHE_DB, tradeNo)) {
                if (RedisTools.get().set(RedisDBConstants.ORDER_CACHE_DB, tradeNo, JsonTools.toJson(orderCollect), times)) {
                    return orderCollect;
                }
            } else {
                log.error("创建便捷线充租借订单时，订单号冲突，订单号：{{0}}",tradeNo);
                throw new LogicException("系统繁忙，请稍后再试");
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return null;
    }
    
    public static CacheOrderCollect buildPCLCacheOrderCollect(LoginMember loginMember, Device device, ChargingCable chargingCable, PCLFeeTemplate freightBasis
            , SetMealContent.Item setMealItem, DefaultAlipayConfig payConfig, OperateInfo operateInfo) throws LogicException {
        PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(device.getPlaceId());
        if(physicalStore == null) {
            throw new LogicException("未找到设备部署的网点信息");
        }
        String tradeNo = OrderTradeNoPrefix.PCL_DEVICE_ORDER + IDTools.getTimestampSecondID() + String.format("%03d", counter.getAndIncrement());
        Date createDate = new Date();

        CacheOrderCollect orderCollect = new CacheOrderCollect();
        AlipayOrder payOrder = new AlipayOrder();
        payOrder.setTradeNo(tradeNo);
        payOrder.setTitle("便捷线充租借");
        payOrder.setNote("会员[" + loginMember.getNickname() + "]便捷线充租借");
        payOrder.setBusinessType(EBusinessType.PCL.index());
        payOrder.setBusinessTypeName(EBusinessType.PCL.note());
        payOrder.setBusinessTradeNo(tradeNo);
        payOrder.setAppType(AlipayConfigEnum.AppType.alixcx.index());
        payOrder.setAppId(payConfig.getAppId());
        payOrder.setPayerId(loginMember.getOpenId());
        payOrder.setBusinessAccount(payConfig.getPid());
        payOrder.setTradeType(TradeType.Normal.name());
        payOrder.setPayMoney(setMealItem.getMoney());
        payOrder.setNotifyUrl(payConfig.getPayNotifyUrl());
        payOrder.setCreateDate(createDate);
        
		try {
			InetAddress inetAddress = InetAddress.getLocalHost();
			 String ip = inetAddress.getHostAddress();
		        payOrder.setClientIP(ip);
		} catch (UnknownHostException e) {
			log.error("获取服务器IP失败，错误：" + e.getMessage(), e);
		}
       
        orderCollect.setAlipayOrder(payOrder);

        PCLOrder deviceOrder = new PCLOrder();
        deviceOrder.setTradeNo(tradeNo);

        deviceOrder.setDeviceTypeId(device.getDeviceTypeId());
        deviceOrder.setDeviceTypeName(device.getDeviceTypeName());
        deviceOrder.setChargingCableSn(device.getDeviceSn());
        deviceOrder.setPlaceId(device.getPlaceId());
        deviceOrder.setPlaceName(device.getPlaceName());
        deviceOrder.setProvince(device.getProvince());
        deviceOrder.setCity(device.getCity());
        deviceOrder.setCityArea(device.getCityArea());
        deviceOrder.setAreaCode(device.getAreaCode());
        deviceOrder.setAddress(physicalStore.getAddress());
        deviceOrder.setLatitude(physicalStore.getLatitude());
        deviceOrder.setLongitude(physicalStore.getLongitude());
        deviceOrder.setAgentId(physicalStore.getUserId());

        deviceOrder.setMemberId(loginMember.getId());
        deviceOrder.setMemberName(loginMember.getNickname());
        deviceOrder.setMemberPhone(loginMember.getPhone());

        deviceOrder.setCostMode(EPCLCostMode.SetMeal.index());
        deviceOrder.setSetMealId(setMealItem.getId());
        deviceOrder.setSetMealName(setMealItem.getName());
        deviceOrder.setUseTimes(setMealItem.getTimes());

        deviceOrder.setPayType(EPayType.Alipay.index());
        deviceOrder.setPayTradeNo(tradeNo);
        deviceOrder.setCreateDate(createDate);

        orderCollect.setPclOrder(deviceOrder);

        OrderLogContent logContent = new OrderLogContent();
        OrderLogContent.LogItem logItem = new OrderLogContent.LogItem();
        logItem.setCreateDate(createDate);
        if (StringTools.isNotBlank(operateInfo.getOperateNote())) {
            logItem.setContent("创建租借订单，" + operateInfo.getOperateNote());
        } else {
            logItem.setContent("创建租借订单");
        }
        logItem.setState(ELogState.Success.index());
        logItem.setProgramTypeName(operateInfo.getProgramTypeName());
        logItem.setOperatorType(operateInfo.getOperatorType());
        logItem.setOperatorTypeName(operateInfo.getOperatorTypeName());
        logItem.setOperator(operateInfo.getOperator());
        logContent.getItems().add(logItem);

        orderCollect.setLogContent(logContent);

        try {
            if (!RedisTools.get().exists(RedisDBConstants.ORDER_CACHE_DB, tradeNo)) {
                if (RedisTools.get().set(RedisDBConstants.ORDER_CACHE_DB, tradeNo, JsonTools.toJson(orderCollect), times)) {
                    return orderCollect;
                }
            } else {
                log.error("创建便捷线充租借订单时，订单号冲突，订单号：{{0}}",tradeNo);
                throw new LogicException("系统繁忙，请稍后再试");
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public static CacheOrderCollect buildBXSCNCacheOrderCollect(LoginMember loginMember, Device device, PortableEnergyCabinet portableEnergyCabinet, BXSCNFeeTemplate freightBasis
            , DefaultWXPayConfig payConfig, OperateInfo operateInfo) throws LogicException {
        PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(device.getPlaceId());
        if(physicalStore == null) {
            throw new LogicException("未找到设备部署的网点信息");
        }
        String tradeNo = OrderTradeNoPrefix.BXSCN_DEVICE_ORDER + IDTools.getTimestampSecondID() + String.format("%03d", counter.getAndIncrement());
        Date createDate = new Date();
        Integer depositMoney = freightBasis.getDepositMoney();

        CacheOrderCollect orderCollect = new CacheOrderCollect();
        WXPayOrder payOrder = new WXPayOrder();
        payOrder.setTradeNo(tradeNo);
        payOrder.setTitle("便携式储能电池租借");
        payOrder.setNote("会员[" + loginMember.getNickname() + "]储能电池租借");
        payOrder.setBusinessType(EBusinessType.BXSCN.index());
        payOrder.setBusinessTypeName(EBusinessType.BXSCN.note());
        payOrder.setBusinessTradeNo(tradeNo);
        payOrder.setAppType(WXPayConfigEnum.AppType.wxxcx.index());
        payOrder.setAppId(payConfig.getAppId());
        payOrder.setPayerId(loginMember.getOpenId());
        payOrder.setBusinessAccount(payConfig.getMchId());
        payOrder.setTradeType(TradeType.Normal.name());
        payOrder.setPayMoney(depositMoney);
        payOrder.setClientIP(payConfig.getServerIp());
        payOrder.setNotifyUrl(payConfig.getPayNotifyUrl());
        payOrder.setCreateDate(createDate);

        orderCollect.setPayOrder(payOrder);

        BXSCNOrder deviceOrder = new BXSCNOrder();
        deviceOrder.setTradeNo(tradeNo);

        deviceOrder.setLeaseDeviceTypeId(device.getDeviceTypeId());
        deviceOrder.setLeaseDeviceTypeName(device.getDeviceTypeName());
        deviceOrder.setLeaseDeviceSn(device.getDeviceSn());
        deviceOrder.setLeaseBindNote(device.getBindNote());
        deviceOrder.setLeaseIotId(portableEnergyCabinet.getIotNodeId());
        deviceOrder.setLeasePlaceId(device.getPlaceId());
        deviceOrder.setLeasePlaceName(device.getPlaceName());
        deviceOrder.setLeaseProvince(device.getProvince());
        deviceOrder.setLeaseCity(device.getCity());
        deviceOrder.setLeaseCityArea(device.getCityArea());
        deviceOrder.setLeaseAddress(physicalStore.getAddress());
        deviceOrder.setLeaseLatitude(physicalStore.getLatitude());
        deviceOrder.setLeaseLongitude(physicalStore.getLongitude());
        deviceOrder.setLeaseAgentId(physicalStore.getUserId());

        deviceOrder.setMemberId(loginMember.getId());
        deviceOrder.setMemberName(loginMember.getNickname());
        deviceOrder.setMemberPhone(loginMember.getPhone());

        deviceOrder.setCostMode(EBXSCNCostMode.Deposit.index());
        deviceOrder.setDepositMoney(freightBasis.getDepositMoney());
        deviceOrder.setFreeTimes(freightBasis.getFreeTimes());
        deviceOrder.setPayIntervalMoney(freightBasis.getPayIntervalMoney());
        deviceOrder.setDayMaxMoney(freightBasis.getDayMaxMoney());

        deviceOrder.setPayType(EPayType.WXPay.index());
        deviceOrder.setPayTradeNo(tradeNo);
        deviceOrder.setCreateDate(createDate);

        orderCollect.setBxscnOrder(deviceOrder);

        OrderLogContent logContent = new OrderLogContent();
        OrderLogContent.LogItem logItem = new OrderLogContent.LogItem();
        logItem.setCreateDate(createDate);
        if (StringTools.isNotBlank(operateInfo.getOperateNote())) {
            logItem.setContent("创建租借订单，" + operateInfo.getOperateNote());
        } else {
            logItem.setContent("创建租借订单");
        }
        logItem.setState(ELogState.Success.index());
        logItem.setProgramTypeName(operateInfo.getProgramTypeName());
        logItem.setOperatorType(operateInfo.getOperatorType());
        logItem.setOperatorTypeName(operateInfo.getOperatorTypeName());
        logItem.setOperator(operateInfo.getOperator());
        logContent.getItems().add(logItem);

        orderCollect.setLogContent(logContent);

        try {
            if (!RedisTools.get().exists(RedisDBConstants.ORDER_CACHE_DB, tradeNo)) {
                if (RedisTools.get().set(RedisDBConstants.ORDER_CACHE_DB, tradeNo, JsonTools.toJson(orderCollect), times)) {
                    return orderCollect;
                }
            } else {
                log.error("创建便携式储能电池租借订单时，订单号冲突，订单号：{{0}}",tradeNo);
                throw new LogicException("系统繁忙，请稍后再试");
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return null;
    }
    
    public static CacheOrderCollect buildBXSCNCacheOrderCollect(LoginMember loginMember, Device device, PortableEnergyCabinet portableEnergyCabinet, BXSCNFeeTemplate freightBasis
            , DefaultAlipayConfig payConfig, OperateInfo operateInfo) throws LogicException {
        PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(device.getPlaceId());
        if(physicalStore == null) {
            throw new LogicException("未找到设备部署的网点信息");
        }
        String tradeNo = OrderTradeNoPrefix.BXSCN_DEVICE_ORDER + IDTools.getTimestampSecondID() + String.format("%03d", counter.getAndIncrement());
        Date createDate = new Date();
        Integer depositMoney = freightBasis.getDepositMoney();

        CacheOrderCollect orderCollect = new CacheOrderCollect();
        AlipayOrder payOrder = new AlipayOrder();
        payOrder.setTradeNo(tradeNo);
        payOrder.setTitle("便携式储能电池租借");
        payOrder.setNote("会员[" + loginMember.getNickname() + "]储能电池租借");
        payOrder.setBusinessType(EBusinessType.BXSCN.index());
        payOrder.setBusinessTypeName(EBusinessType.BXSCN.note());
        payOrder.setBusinessTradeNo(tradeNo);
        payOrder.setAppType(AlipayConfigEnum.AppType.alixcx.index());
        payOrder.setAppId(payConfig.getAppId());
        payOrder.setPayerId(loginMember.getOpenId());
        payOrder.setBusinessAccount(payConfig.getPid());
        payOrder.setTradeType(TradeType.Normal.name());
        payOrder.setPayMoney(depositMoney);
        payOrder.setNotifyUrl(payConfig.getPayNotifyUrl());
        payOrder.setCreateDate(createDate);
        
        orderCollect.setAlipayOrder(payOrder);

        BXSCNOrder deviceOrder = new BXSCNOrder();
        deviceOrder.setTradeNo(tradeNo);

        deviceOrder.setLeaseDeviceTypeId(device.getDeviceTypeId());
        deviceOrder.setLeaseDeviceTypeName(device.getDeviceTypeName());
        deviceOrder.setLeaseDeviceSn(device.getDeviceSn());
        deviceOrder.setLeaseBindNote(device.getBindNote());
        deviceOrder.setLeaseIotId(portableEnergyCabinet.getIotNodeId());
        deviceOrder.setLeasePlaceId(device.getPlaceId());
        deviceOrder.setLeasePlaceName(device.getPlaceName());
        deviceOrder.setLeaseProvince(device.getProvince());
        deviceOrder.setLeaseCity(device.getCity());
        deviceOrder.setLeaseCityArea(device.getCityArea());
        deviceOrder.setLeaseAddress(physicalStore.getAddress());
        deviceOrder.setLeaseLatitude(physicalStore.getLatitude());
        deviceOrder.setLeaseLongitude(physicalStore.getLongitude());
        deviceOrder.setLeaseAgentId(physicalStore.getUserId());

        deviceOrder.setMemberId(loginMember.getId());
        deviceOrder.setMemberName(loginMember.getNickname());
        deviceOrder.setMemberPhone(loginMember.getPhone());

        deviceOrder.setCostMode(EBXSCNCostMode.Deposit.index());
        deviceOrder.setDepositMoney(freightBasis.getDepositMoney());
        deviceOrder.setFreeTimes(freightBasis.getFreeTimes());
        deviceOrder.setPayIntervalMoney(freightBasis.getPayIntervalMoney());
        deviceOrder.setDayMaxMoney(freightBasis.getDayMaxMoney());

        deviceOrder.setPayType(EPayType.Alipay.index());
        deviceOrder.setPayTradeNo(tradeNo);
        deviceOrder.setCreateDate(createDate);

        orderCollect.setBxscnOrder(deviceOrder);

        OrderLogContent logContent = new OrderLogContent();
        OrderLogContent.LogItem logItem = new OrderLogContent.LogItem();
        logItem.setCreateDate(createDate);
        if (StringTools.isNotBlank(operateInfo.getOperateNote())) {
            logItem.setContent("创建租借订单，" + operateInfo.getOperateNote());
        } else {
            logItem.setContent("创建租借订单");
        }
        logItem.setState(ELogState.Success.index());
        logItem.setProgramTypeName(operateInfo.getProgramTypeName());
        logItem.setOperatorType(operateInfo.getOperatorType());
        logItem.setOperatorTypeName(operateInfo.getOperatorTypeName());
        logItem.setOperator(operateInfo.getOperator());
        logContent.getItems().add(logItem);

        orderCollect.setLogContent(logContent);

        try {
            if (!RedisTools.get().exists(RedisDBConstants.ORDER_CACHE_DB, tradeNo)) {
                if (RedisTools.get().set(RedisDBConstants.ORDER_CACHE_DB, tradeNo, JsonTools.toJson(orderCollect), times)) {
                    return orderCollect;
                }
            } else {
                log.error("创建便携式储能电池租借订单时，订单号冲突，订单号：{{0}}",tradeNo);
                throw new LogicException("系统繁忙，请稍后再试");
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public static CacheOrderCollect buildBXSCNShopCacheOrderCollect(LoginMember loginMember, PlacePhysicalStore physicalStore, BXSCNShopLeaseConfig bxscnShopLeaseConfig
            ,DefaultWXPayConfig payConfig, OperateInfo operateInfo) throws LogicException {
        String tradeNo = OrderTradeNoPrefix.BXSCN_SHOP_DEVICE_ORDER + IDTools.getTimestampSecondID() + String.format("%03d", counter.getAndIncrement());
        Date createDate = new Date();

        PortableEnergyBatteryType portableEnergyBatteryType = PortableEnergyBatteryTypeService.self().getById(bxscnShopLeaseConfig.getBatteryType());
        if(portableEnergyBatteryType == null){
            throw new LogicException(bxscnShopLeaseConfig.getBatteryType() + "类型电池不存在");
        }
        
        //价格配置
        Long feeTemplateId = null;
        BXSCNShopFeeTemplateItem templateItem = null;
        
        Integer type = BXSCNShopFeeTemplateItemEnum.Type.Normal.index();
        Integer depositMoney = 0;
        Integer dayMoney = 0;
        Integer timeoutDayMoney = 0;
        BXSCNBatteryTypeDayMoneyContent dayMoneyContent = null;
        
        PlaceBusinessConfig placeBusiConfig = PlaceBusinessConfigService.self().getByKeys(physicalStore.getId(),EBusinessType.BXSCN_SHOP.index());
        if(placeBusiConfig != null && placeBusiConfig.getFeeTemplateId() != null) {
        	feeTemplateId = placeBusiConfig.getFeeTemplateId();
        }

        if(feeTemplateId != null) {
        	Integer feeTemplateType = BXSCNShopFeeTemplateItemEnum.Type.Normal.index();
    	    if(bxscnShopLeaseConfig.getMemberType() != null && EMemberBusinessType.FreeMember.index().equals(bxscnShopLeaseConfig.getMemberType())) {
    		   feeTemplateType = BXSCNShopFeeTemplateItemEnum.Type.FreeMember.index();
    	    }
        	templateItem = BXSCNShopFeeTemplateService.self().getItemByAvailable(feeTemplateId, portableEnergyBatteryType.getId(),feeTemplateType);
        }

        if(templateItem != null) {
        	type = templateItem.getType();
        	depositMoney = templateItem.getDepositMoney();
            dayMoney = templateItem.getDayMoney();
            timeoutDayMoney = templateItem.getDayMoney();

            if (StringTools.isNotBlank(templateItem.getDayMoneyContent())) {
                dayMoneyContent = JsonTools.fromJson(templateItem.getDayMoneyContent(), BXSCNBatteryTypeDayMoneyContent.class);
            }
        }else {
        	BXSCNBatteryTypeDayCost costConfig = BXSCNBatteryTypeDayCostService.self().getByTypeId(portableEnergyBatteryType.getId());
            if(costConfig == null){
                throw new LogicException("未配置租借费用");
            }
            
            depositMoney = costConfig.getDepositMoney();
            dayMoney = costConfig.getDayMoney();
            timeoutDayMoney = costConfig.getDayMoney();

            if (StringTools.isNotBlank(costConfig.getDayMoneyContent())) {
                dayMoneyContent = JsonTools.fromJson(costConfig.getDayMoneyContent(), BXSCNBatteryTypeDayMoneyContent.class);
            }
        }
        
        if (dayMoneyContent != null && dayMoneyContent.getItems() != null && dayMoneyContent.getItems().size() > 0) {
            for (BXSCNBatteryTypeDayMoneyContent.Item item : dayMoneyContent.getItems()) {
                if (item.getLeaseDay() <= bxscnShopLeaseConfig.getLeaseDay()) {
                    dayMoney = item.getMoney();
                } else {
                    break;
                }
            }
        }
        
        //计算金额
        Integer payMoney = depositMoney + (dayMoney * bxscnShopLeaseConfig.getLeaseDay());

        Long money = NumberTools.changeMoneyLi(NumberTools.changeMoney(payMoney));

        CacheOrderCollect orderCollect = new CacheOrderCollect();
        WXPayOrder payOrder = new WXPayOrder();
        payOrder.setTradeNo(tradeNo);
        payOrder.setTitle("便携式储能电池租借");
        payOrder.setNote(physicalStore.getName());
        payOrder.setBusinessType(EBusinessType.BXSCN_SHOP.index());
        payOrder.setBusinessTypeName(EBusinessType.BXSCN_SHOP.note());
        payOrder.setBusinessTradeNo(tradeNo);
        payOrder.setAppType(WXPayConfigEnum.AppType.wxxcx.index());
        payOrder.setAppId(payConfig.getAppId());
        payOrder.setPayerId(loginMember.getOpenId());
        payOrder.setBusinessAccount(payConfig.getMchId());
        payOrder.setTradeType(TradeType.Normal.name());
        payOrder.setPayMoney(payMoney);
        payOrder.setClientIP(payConfig.getServerIp());
        payOrder.setNotifyUrl(payConfig.getPayNotifyUrl());
        payOrder.setCreateDate(createDate);

        orderCollect.setPayOrder(payOrder);

        BXSCNShopOrder deviceOrder = new BXSCNShopOrder();
        deviceOrder.setTradeNo(tradeNo);
        deviceOrder.setLeaseType(bxscnShopLeaseConfig.getLeaseType());
        deviceOrder.setBatteryType(portableEnergyBatteryType.getId());
        deviceOrder.setBatteryTypeName(portableEnergyBatteryType.getName());
        deviceOrder.setBatteryPower(portableEnergyBatteryType.getBatteryPower());

        deviceOrder.setLeasePlaceId(physicalStore.getId());
        deviceOrder.setLeasePlaceName(physicalStore.getName());
        deviceOrder.setLeaseProvince(physicalStore.getProvince());
        deviceOrder.setLeaseCity(physicalStore.getCity());
        deviceOrder.setLeaseCityArea(physicalStore.getCityArea());
        deviceOrder.setLeaseAreaCode(physicalStore.getAreaCode());
        deviceOrder.setLeaseAddress(physicalStore.getAddress());
        deviceOrder.setLeaseLatitude(physicalStore.getLatitude());
        deviceOrder.setLeaseLongitude(physicalStore.getLongitude());
        deviceOrder.setLeaseAgentId(physicalStore.getUserId());

        deviceOrder.setMemberId(loginMember.getId());
        deviceOrder.setMemberName(loginMember.getNickname());
        deviceOrder.setMemberPhone(loginMember.getPhone());

        deviceOrder.setDepositMoney(depositMoney);
        deviceOrder.setDayMoney(dayMoney);
        deviceOrder.setTimeoutDayMoney(timeoutDayMoney);
        deviceOrder.setLeaseDay(bxscnShopLeaseConfig.getLeaseDay());
       
        if(BXSCNShopFeeTemplateItemEnum.Type.FreeMember.index().equals(type)) {
        	deviceOrder.setDiscountType(EDiscountType.FreeMember.index());
        }
        
        deviceOrder.setPayType(EPayType.WXPay.index());
        deviceOrder.setMoney(money);
        deviceOrder.setPayMoney(payMoney);
        deviceOrder.setWalletMoney(0L);
        deviceOrder.setPayTradeNo(tradeNo);
        deviceOrder.setCreateDate(createDate);

        //设置时间
        deviceOrder.setStartDate(bxscnShopLeaseConfig.getLeaseStartDate());       //开始时间
        deviceOrder.setEndDate(DateUtils.addDays(bxscnShopLeaseConfig.getLeaseStartDate(), bxscnShopLeaseConfig.getLeaseDay()));

        orderCollect.setBxscnShopOrder(deviceOrder);

        OrderLogContent logContent = new OrderLogContent();
        OrderLogContent.LogItem logItem = new OrderLogContent.LogItem();
        logItem.setCreateDate(createDate);
        logItem.setContent("创建订单");
        logItem.setState(ELogState.Success.index());
        logItem.setProgramTypeName(operateInfo.getProgramTypeName());
        logItem.setOperatorType(operateInfo.getOperatorType());
        logItem.setOperatorTypeName(operateInfo.getOperatorTypeName());
        logItem.setOperator(operateInfo.getOperator());
        logContent.getItems().add(logItem);

        orderCollect.setLogContent(logContent);

        try {
            if (!RedisTools.get().exists(RedisDBConstants.ORDER_CACHE_DB, tradeNo)) {
                if (RedisTools.get().set(RedisDBConstants.ORDER_CACHE_DB, tradeNo, JsonTools.toJson(orderCollect), times)) {
                    return orderCollect;
                }
            } else {
                log.error("创建充电插座订单时，订单号冲突，订单号：{{0}}",tradeNo);
                throw new LogicException("系统繁忙，请稍后再试");
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return null;
    }
    
    public static CacheOrderCollect buildBXSCNShopCacheOrderCollect(LoginMember loginMember, PlacePhysicalStore physicalStore, BXSCNShopLeaseConfig bxscnShopLeaseConfig
            ,DefaultAlipayConfig payConfig, OperateInfo operateInfo) throws LogicException {
        String tradeNo = OrderTradeNoPrefix.BXSCN_SHOP_DEVICE_ORDER + IDTools.getTimestampSecondID() + String.format("%03d", counter.getAndIncrement());
        Date createDate = new Date();

        PortableEnergyBatteryType portableEnergyBatteryType = PortableEnergyBatteryTypeService.self().getById(bxscnShopLeaseConfig.getBatteryType());
        if(portableEnergyBatteryType == null){
            throw new LogicException(bxscnShopLeaseConfig.getBatteryType() + "类型电池不存在");
        }
        
        //价格配置
        Long feeTemplateId = null;
        BXSCNShopFeeTemplateItem templateItem = null;
        
        Integer type = BXSCNShopFeeTemplateItemEnum.Type.Normal.index();
        Integer depositMoney = 0;
        Integer dayMoney = 0;
        Integer timeoutDayMoney = 0;
        BXSCNBatteryTypeDayMoneyContent dayMoneyContent = null;
        
        PlaceBusinessConfig placeBusiConfig = PlaceBusinessConfigService.self().getByKeys(physicalStore.getId(),EBusinessType.BXSCN_SHOP.index());
        if(placeBusiConfig != null && placeBusiConfig.getFeeTemplateId() != null) {
        	feeTemplateId = placeBusiConfig.getFeeTemplateId();
        }

        if(feeTemplateId != null) {
        	Integer feeTemplateType = BXSCNShopFeeTemplateItemEnum.Type.Normal.index();
    	    if(bxscnShopLeaseConfig.getMemberType() != null && EMemberBusinessType.FreeMember.index().equals(bxscnShopLeaseConfig.getMemberType())) {
    		   feeTemplateType = BXSCNShopFeeTemplateItemEnum.Type.FreeMember.index();
    	    }
        	templateItem = BXSCNShopFeeTemplateService.self().getItemByAvailable(feeTemplateId, portableEnergyBatteryType.getId(),feeTemplateType);
        }

        if(templateItem != null) {
        	type = templateItem.getType();
        	depositMoney = templateItem.getDepositMoney();
            dayMoney = templateItem.getDayMoney();
            timeoutDayMoney = templateItem.getDayMoney();

            if (StringTools.isNotBlank(templateItem.getDayMoneyContent())) {
                dayMoneyContent = JsonTools.fromJson(templateItem.getDayMoneyContent(), BXSCNBatteryTypeDayMoneyContent.class);
            }
        }else {
        	BXSCNBatteryTypeDayCost costConfig = BXSCNBatteryTypeDayCostService.self().getByTypeId(portableEnergyBatteryType.getId());
            if(costConfig == null){
                throw new LogicException("未配置租借费用");
            }
            
            depositMoney = costConfig.getDepositMoney();
            dayMoney = costConfig.getDayMoney();
            timeoutDayMoney = costConfig.getDayMoney();

            if (StringTools.isNotBlank(costConfig.getDayMoneyContent())) {
                dayMoneyContent = JsonTools.fromJson(costConfig.getDayMoneyContent(), BXSCNBatteryTypeDayMoneyContent.class);
            }
        }
        
        if (dayMoneyContent != null && dayMoneyContent.getItems() != null && dayMoneyContent.getItems().size() > 0) {
            for (BXSCNBatteryTypeDayMoneyContent.Item item : dayMoneyContent.getItems()) {
                if (item.getLeaseDay() <= bxscnShopLeaseConfig.getLeaseDay()) {
                    dayMoney = item.getMoney();
                } else {
                    break;
                }
            }
        }
        
        //计算金额
        Integer payMoney = depositMoney + (dayMoney * bxscnShopLeaseConfig.getLeaseDay());

        Long money = NumberTools.changeMoneyLi(NumberTools.changeMoney(payMoney));

        CacheOrderCollect orderCollect = new CacheOrderCollect();
        AlipayOrder payOrder = new AlipayOrder();
        payOrder.setTradeNo(tradeNo);
        payOrder.setTitle("便携式储能电池租借");
        payOrder.setNote("会员[" + loginMember.getNickname() + "]租借" + physicalStore.getName());
        payOrder.setBusinessType(EBusinessType.BXSCN_SHOP.index());
        payOrder.setBusinessTypeName(EBusinessType.BXSCN_SHOP.note());
        payOrder.setBusinessTradeNo(tradeNo);
        payOrder.setAppType(AlipayConfigEnum.AppType.alixcx.index());
        payOrder.setAppId(payConfig.getAppId());
        payOrder.setPayerId(loginMember.getOpenId());
        payOrder.setBusinessAccount(payConfig.getPid());
        payOrder.setTradeType(TradeType.Normal.name());
        payOrder.setPayMoney(payMoney);
        payOrder.setNotifyUrl(payConfig.getPayNotifyUrl());
        payOrder.setCreateDate(createDate);
        
        orderCollect.setAlipayOrder(payOrder);

        BXSCNShopOrder deviceOrder = new BXSCNShopOrder();
        deviceOrder.setTradeNo(tradeNo);
        deviceOrder.setLeaseType(bxscnShopLeaseConfig.getLeaseType());
        deviceOrder.setBatteryType(portableEnergyBatteryType.getId());
        deviceOrder.setBatteryTypeName(portableEnergyBatteryType.getName());
        deviceOrder.setBatteryPower(portableEnergyBatteryType.getBatteryPower());

        deviceOrder.setLeasePlaceId(physicalStore.getId());
        deviceOrder.setLeasePlaceName(physicalStore.getName());
        deviceOrder.setLeaseProvince(physicalStore.getProvince());
        deviceOrder.setLeaseCity(physicalStore.getCity());
        deviceOrder.setLeaseCityArea(physicalStore.getCityArea());
        deviceOrder.setLeaseAreaCode(physicalStore.getAreaCode());
        deviceOrder.setLeaseAddress(physicalStore.getAddress());
        deviceOrder.setLeaseLatitude(physicalStore.getLatitude());
        deviceOrder.setLeaseLongitude(physicalStore.getLongitude());
        deviceOrder.setLeaseAgentId(physicalStore.getUserId());

        deviceOrder.setMemberId(loginMember.getId());
        deviceOrder.setMemberName(loginMember.getNickname());
        deviceOrder.setMemberPhone(loginMember.getPhone());

        deviceOrder.setDepositMoney(depositMoney);
        deviceOrder.setDayMoney(dayMoney);
        deviceOrder.setTimeoutDayMoney(timeoutDayMoney);
        deviceOrder.setLeaseDay(bxscnShopLeaseConfig.getLeaseDay());
       
        if(BXSCNShopFeeTemplateItemEnum.Type.FreeMember.index().equals(type)) {
        	deviceOrder.setDiscountType(EDiscountType.FreeMember.index());
        }
        
        deviceOrder.setPayType(EPayType.Alipay.index());
        deviceOrder.setMoney(money);
        deviceOrder.setPayMoney(payMoney);
        deviceOrder.setWalletMoney(0L);
        deviceOrder.setPayTradeNo(tradeNo);
        deviceOrder.setCreateDate(createDate);

        //设置时间
        deviceOrder.setStartDate(bxscnShopLeaseConfig.getLeaseStartDate());       //开始时间
        deviceOrder.setEndDate(DateUtils.addDays(bxscnShopLeaseConfig.getLeaseStartDate(), bxscnShopLeaseConfig.getLeaseDay()));

        orderCollect.setBxscnShopOrder(deviceOrder);

        OrderLogContent logContent = new OrderLogContent();
        OrderLogContent.LogItem logItem = new OrderLogContent.LogItem();
        logItem.setCreateDate(createDate);
        logItem.setContent("创建订单");
        logItem.setState(ELogState.Success.index());
        logItem.setProgramTypeName(operateInfo.getProgramTypeName());
        logItem.setOperatorType(operateInfo.getOperatorType());
        logItem.setOperatorTypeName(operateInfo.getOperatorTypeName());
        logItem.setOperator(operateInfo.getOperator());
        logContent.getItems().add(logItem);

        orderCollect.setLogContent(logContent);

        try {
            if (!RedisTools.get().exists(RedisDBConstants.ORDER_CACHE_DB, tradeNo)) {
                if (RedisTools.get().set(RedisDBConstants.ORDER_CACHE_DB, tradeNo, JsonTools.toJson(orderCollect), times)) {
                    return orderCollect;
                }
            } else {
                log.error("创建充电插座订单时，订单号冲突，订单号：{{0}}",tradeNo);
                throw new LogicException("系统繁忙，请稍后再试");
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return null;
    }

    /**
     * 使用会员钱包
     * @param loginMember
     * @param physicalStore
     * @param bxscnShopLeaseConfig
     * @param operateInfo
     * @return
     * @throws LogicException
     */
    public static CacheOrderCollect buildBXSCNShopCacheOrderCollect(LoginMember loginMember, PlacePhysicalStore physicalStore, 
    		BXSCNShopLeaseConfig bxscnShopLeaseConfig , OperateInfo operateInfo) throws LogicException {
        String tradeNo = OrderTradeNoPrefix.BXSCN_SHOP_DEVICE_ORDER + IDTools.getTimestampSecondID() + String.format("%03d", counter.getAndIncrement());
        Date createDate = new Date();

        PortableEnergyBatteryType portableEnergyBatteryType = PortableEnergyBatteryTypeService.self().getById(bxscnShopLeaseConfig.getBatteryType());
        if(portableEnergyBatteryType == null){
            throw new LogicException(bxscnShopLeaseConfig.getBatteryType() + "类型电池不存在");
        }
        
        //价格配置
        Long feeTemplateId = null;
        BXSCNShopFeeTemplateItem templateItem = null;
        
        Integer type = BXSCNShopFeeTemplateItemEnum.Type.Normal.index();
        Integer depositMoney = 0;
        Integer dayMoney = 0;
        Integer timeoutDayMoney = 0;
        BXSCNBatteryTypeDayMoneyContent dayMoneyContent = null;
        
        PlaceBusinessConfig placeBusiConfig = PlaceBusinessConfigService.self().getByKeys(physicalStore.getId(),EBusinessType.BXSCN_SHOP.index());
        if(placeBusiConfig != null && placeBusiConfig.getFeeTemplateId() != null) {
        	feeTemplateId = placeBusiConfig.getFeeTemplateId();
        }

        if(feeTemplateId != null) {
        	Integer feeTemplateType = BXSCNShopFeeTemplateItemEnum.Type.Normal.index();
    	    if(bxscnShopLeaseConfig.getMemberType() != null && EMemberBusinessType.FreeMember.index().equals(bxscnShopLeaseConfig.getMemberType())) {
    		   feeTemplateType = BXSCNShopFeeTemplateItemEnum.Type.FreeMember.index();
    	    }
        	templateItem = BXSCNShopFeeTemplateService.self().getItemByAvailable(feeTemplateId, portableEnergyBatteryType.getId(),feeTemplateType);
        }
        
        if(templateItem != null) {
        	type = templateItem.getType();
        	depositMoney = templateItem.getDepositMoney();
            dayMoney = templateItem.getDayMoney();
            timeoutDayMoney = templateItem.getDayMoney();

            if (StringTools.isNotBlank(templateItem.getDayMoneyContent())) {
                dayMoneyContent = JsonTools.fromJson(templateItem.getDayMoneyContent(), BXSCNBatteryTypeDayMoneyContent.class);
            }
        }else {
        	BXSCNBatteryTypeDayCost costConfig = BXSCNBatteryTypeDayCostService.self().getByTypeId(portableEnergyBatteryType.getId());
            if(costConfig == null){
                throw new LogicException("未配置租借费用");
            }
            
            depositMoney = costConfig.getDepositMoney();
            dayMoney = costConfig.getDayMoney();
            timeoutDayMoney = costConfig.getDayMoney();

            if (StringTools.isNotBlank(costConfig.getDayMoneyContent())) {
                dayMoneyContent = JsonTools.fromJson(costConfig.getDayMoneyContent(), BXSCNBatteryTypeDayMoneyContent.class);
            }
        }
        
        if (dayMoneyContent != null && dayMoneyContent.getItems() != null && dayMoneyContent.getItems().size() > 0) {
            for (BXSCNBatteryTypeDayMoneyContent.Item item : dayMoneyContent.getItems()) {
                if (item.getLeaseDay() <= bxscnShopLeaseConfig.getLeaseDay()) {
                    dayMoney = item.getMoney();
                } else {
                    break;
                }
            }
        }
      
        //计算金额
        Integer payMoney = depositMoney + (dayMoney * bxscnShopLeaseConfig.getLeaseDay());

        Long money = NumberTools.changeMoneyLi(NumberTools.changeMoney(payMoney));
        if (!MemberWalletService.self().hasMoney(loginMember.getId(),money)){
            throw new LogicException("余额不足");
        }

        CacheOrderCollect orderCollect = new CacheOrderCollect();

        BXSCNShopOrder deviceOrder = new BXSCNShopOrder();
        deviceOrder.setTradeNo(tradeNo);
        deviceOrder.setLeaseType(bxscnShopLeaseConfig.getLeaseType());
        deviceOrder.setBatteryType(portableEnergyBatteryType.getId());
        deviceOrder.setBatteryTypeName(portableEnergyBatteryType.getName());

        deviceOrder.setLeasePlaceId(physicalStore.getId());
        deviceOrder.setLeasePlaceName(physicalStore.getName());
        deviceOrder.setLeaseProvince(physicalStore.getProvince());
        deviceOrder.setLeaseCity(physicalStore.getCity());
        deviceOrder.setLeaseCityArea(physicalStore.getCityArea());
        deviceOrder.setLeaseAreaCode(physicalStore.getAreaCode());
        deviceOrder.setLeaseAddress(physicalStore.getAddress());
        deviceOrder.setLeaseLatitude(physicalStore.getLatitude());
        deviceOrder.setLeaseLongitude(physicalStore.getLongitude());
        deviceOrder.setLeaseAgentId(physicalStore.getUserId());

        deviceOrder.setMemberId(loginMember.getId());
        deviceOrder.setMemberName(loginMember.getNickname());
        deviceOrder.setMemberPhone(loginMember.getPhone());

        deviceOrder.setDepositMoney(depositMoney);
        deviceOrder.setDayMoney(dayMoney);
        deviceOrder.setTimeoutDayMoney(timeoutDayMoney);
        deviceOrder.setLeaseDay(bxscnShopLeaseConfig.getLeaseDay());
      
        if(BXSCNShopFeeTemplateItemEnum.Type.FreeMember.index().equals(type)) {
        	deviceOrder.setDiscountType(EDiscountType.FreeMember.index());
        }

        deviceOrder.setPayType(EPayType.EWallet.index());
        deviceOrder.setMoney(money);
        deviceOrder.setPayMoney(0);
        deviceOrder.setWalletMoney(money);
        deviceOrder.setCreateDate(createDate);
        
        //设置时间
        deviceOrder.setStartDate(bxscnShopLeaseConfig.getLeaseStartDate());       //开始时间
        deviceOrder.setEndDate(DateUtils.addDays(bxscnShopLeaseConfig.getLeaseStartDate(), bxscnShopLeaseConfig.getLeaseDay()));

        orderCollect.setBxscnShopOrder(deviceOrder);

        OrderLogContent logContent = new OrderLogContent();
        OrderLogContent.LogItem logItem = new OrderLogContent.LogItem();
        logItem.setCreateDate(createDate);
        logItem.setContent("创建订单");
        logItem.setState(ELogState.Success.index());
        logItem.setProgramTypeName(operateInfo.getProgramTypeName());
        logItem.setOperatorType(operateInfo.getOperatorType());
        logItem.setOperatorTypeName(operateInfo.getOperatorTypeName());
        logItem.setOperator(operateInfo.getOperator());
        logContent.getItems().add(logItem);

        orderCollect.setLogContent(logContent);

        operateInfo.setOperateNote("支付" + deviceOrder.getTradeNo() + "订单押金");
        if (BXSCNShopOrderService.self(deviceOrder.getCreateDate()).paySuccess(deviceOrder, orderCollect.getLogContent(),MemberWalletService.self(), operateInfo)) {
            //添加会员订单
            if (MemberBusinessOrderService.self(deviceOrder.getCreateDate()).create(deviceOrder) == null) {
                log.error("充电宝订单创建会员订单失败，订单号：{{0}}", deviceOrder.getTradeNo());
            }
            //触发业务订单创建事件
            JFKafkaProducer producer = KafkaProducerFactory.self().getProducer();
            if (producer != null) {
                OrderCreateEvent event = new OrderCreateEvent(EBusinessType.BXSCN_SHOP.name(), deviceOrder.getTradeNo(), deviceOrder.getCreateDate());
                KafkaMessage kafkaMessage = new KafkaMessage(KafkaEventConstants.TOPIC_Order,
                        KafkaEventConstants.KEY_OrderCreate, JsonTools.toJson(event));
                producer.send(kafkaMessage);
            } else {
                log.error("消息队列未初始化");
            }
            return orderCollect;
        }
        return null;
    }

    public static void saveWXPayOrderExternalContent(String tradeNo, String externalContent) {
        try {
            RedisTools.get().set(RedisDBConstants.PAY_EXTERNAL_ORDER_CACHE_DB, tradeNo, externalContent, times);
        }catch (Exception e){
            log.error("缓存微信支付参数错误，订单：{{0}}，内容：{{1}}",tradeNo,externalContent);
            log.error(e.getMessage(),e);
        }
    }
    
    public static void saveAlipayOrderExternalContent(String tradeNo, String externalContent) {
        try {
            RedisTools.get().set(RedisDBConstants.PAY_EXTERNAL_ORDER_CACHE_DB, tradeNo, externalContent, times);
        }catch (Exception e){
            log.error("缓存支付宝支付参数错误，订单：{{0}}，内容：{{1}}",tradeNo,externalContent);
            log.error(e.getMessage(),e);
        }
    }

    public static void payResult(final WXPayNormalPayNotify notify, OperateInfo operateInfo) {
        String json = null;
        CacheOrderCollect orderCollect = null;
        WXPayOrder payOrder = null;
        try {
            json = RedisTools.get().getAndRemove(RedisDBConstants.ORDER_CACHE_DB, notify.getOut_trade_no());
            if (StringTools.isNotBlank(json)) {
                orderCollect = JsonTools.fromJson(json, CacheOrderCollect.class);
                if (orderCollect != null) {
                    payOrder = orderCollect.getPayOrder();
                }
            }
        } catch (Exception e) {
            log.error("微信支付本系统缓存解析失败，微信回调：{{0:json}},缓存内容：{{1}}", notify, json);
            log.error(e.getMessage(), e);
        }

        if (payOrder != null) {
            try {
                int result = WXPayOrderService.self(payOrder.getCreateDate()).payResult(payOrder, notify);
                if (result == 1) {
                    if (EBusinessType.RECHARGE.index().equals(payOrder.getBusinessType())) {
                        MemberRechargeOrder rechargeOrder = orderCollect.getMemberRechargeOrder();
                        rechargeOrder.setPayState(payOrder.getPayStatus());
                        rechargeOrder.setPayMoney(payOrder.getReceiptMoney());
                        rechargeOrder.setPayDate(payOrder.getPayDate());
                        if (MemberRechargeOrderService.self(payOrder.getPayDate()).paySuccess(rechargeOrder, orderCollect.getLogContent(), operateInfo)) {
                            //触发业务订单创建事件
                            JFKafkaProducer producer = KafkaProducerFactory.self().getProducer();
                            if (producer != null) {
                                MemberRechargeFinishEvent event = new MemberRechargeFinishEvent(rechargeOrder.getTradeNo());
                                KafkaMessage kafkaMessage = new KafkaMessage(KafkaEventConstants.TOPIC_Order,
                                        KafkaEventConstants.KEY_MemberRechargeMoney, JsonTools.toJson(event));
                                producer.send(kafkaMessage);
                            } else {
                                log.error("消息队列未初始化");
                            }
                        }
                    } else if (EBusinessType.CDB.index().equals(payOrder.getBusinessType())) {
                        CDBOrder deviceOrder = orderCollect.getCdbOrder();
                        deviceOrder.setPayState(CDBOrderEnum.PayState.DepositSuccess.index());
                        deviceOrder.setPayMoney(payOrder.getReceiptMoney());
                        deviceOrder.setPayDate(payOrder.getPayDate());
                        ICDBNetworkService networkService = HttpNetworkServiceUtils.getCDBNetworkService(deviceOrder.getLeaseIotId());
                        if (CDBOrderService.self(deviceOrder.getCreateDate()).paySuccess(deviceOrder, orderCollect.getLogContent(), networkService, operateInfo)) {
                            //缓存工作中订单
                            RedisCacheManager.saveWorkingCDBDeviceOrder(deviceOrder);
                            //添加会员订单
                            if (MemberBusinessOrderService.self(deviceOrder.getCreateDate()).create(deviceOrder) == null) {
                                log.error("充电宝订单创建会员订单失败，订单号：{{0}}", deviceOrder.getTradeNo());
                            }
                            //触发业务订单创建事件
                            JFKafkaProducer producer = KafkaProducerFactory.self().getProducer();
                            if (producer != null) {
                                OrderCreateEvent event = new OrderCreateEvent(payOrder.getBusinessType(), deviceOrder.getTradeNo(), deviceOrder.getCreateDate());
                                KafkaMessage kafkaMessage = new KafkaMessage(KafkaEventConstants.TOPIC_Order,
                                        KafkaEventConstants.KEY_OrderCreate, JsonTools.toJson(event));
                                producer.send(kafkaMessage);
                            } else {
                                log.error("消息队列未初始化");
                            }
                        } else {
                            log.error("保存共享充电宝订单失败，缓存信息：{{0:json}}", orderCollect);
                        }
                    }else if (EBusinessType.PCL.index().equals(payOrder.getBusinessType())) {
                        PCLOrder deviceOrder = orderCollect.getPclOrder();
                        deviceOrder.setPayState(PCLOrderEnum.PayState.Success.index());
                        deviceOrder.setPayMoney(payOrder.getReceiptMoney());
                        deviceOrder.setPayDate(payOrder.getPayDate());
                        if (PCLOrderService.self(deviceOrder.getCreateDate()).paySuccess(deviceOrder, orderCollect.getLogContent(), operateInfo)) {
                            //缓存工作中订单
                            RedisCacheManager.saveWorkingPCLDeviceOrder(deviceOrder);
                            //添加会员订单
                            if (MemberBusinessOrderService.self(deviceOrder.getCreateDate()).create(deviceOrder) == null) {
                                log.error("充电宝订单创建会员订单失败，订单号：{{0}}", deviceOrder.getTradeNo());
                            }
                            //触发业务订单创建事件
                            JFKafkaProducer producer = KafkaProducerFactory.self().getProducer();
                            if (producer != null) {
                                OrderCreateEvent event = new OrderCreateEvent(payOrder.getBusinessType(), deviceOrder.getTradeNo(), deviceOrder.getCreateDate());
                                KafkaMessage kafkaMessage = new KafkaMessage(KafkaEventConstants.TOPIC_Order,
                                        KafkaEventConstants.KEY_OrderCreate, JsonTools.toJson(event));
                                producer.send(kafkaMessage);
                            } else {
                                log.error("消息队列未初始化");
                            }
                        } else {
                            log.error("保存共享充电宝订单失败，缓存信息：{{0:json}}", orderCollect);
                        }
                    }else if (EBusinessType.BXSCN.index().equals(payOrder.getBusinessType())) {
                        BXSCNOrder deviceOrder = orderCollect.getBxscnOrder();
                        deviceOrder.setPayState(CDBOrderEnum.PayState.DepositSuccess.index());
                        deviceOrder.setPayMoney(payOrder.getReceiptMoney());
                        deviceOrder.setPayDate(payOrder.getPayDate());
                        IBXSCNNetworkService networkService = HttpNetworkServiceUtils.getBXSCNNetworkService(deviceOrder.getLeaseIotId());
                        if (BXSCNOrderService.self(deviceOrder.getCreateDate()).paySuccess(deviceOrder, orderCollect.getLogContent(), networkService, operateInfo)) {
                            //缓存工作中订单
                            RedisCacheManager.saveWorkingBXSCNDeviceOrder(deviceOrder);
                            //添加会员订单
                            if (MemberBusinessOrderService.self(deviceOrder.getCreateDate()).create(deviceOrder) == null) {
                                log.error("便携式储能电池订单创建会员订单失败，订单号：{{0}}", deviceOrder.getTradeNo());
                            }
                            //触发业务订单创建事件
                            JFKafkaProducer producer = KafkaProducerFactory.self().getProducer();
                            if (producer != null) {
                                OrderCreateEvent event = new OrderCreateEvent(payOrder.getBusinessType(), deviceOrder.getTradeNo(), deviceOrder.getCreateDate());
                                KafkaMessage kafkaMessage = new KafkaMessage(KafkaEventConstants.TOPIC_Order,
                                        KafkaEventConstants.KEY_OrderCreate, JsonTools.toJson(event));
                                producer.send(kafkaMessage);
                            } else {
                                log.error("消息队列未初始化");
                            }
                        } else {
                            log.error("保存便携式储能电池租借订单失败，缓存信息：{{0:json}}", orderCollect);
                        }
                    } else if (EBusinessType.BXSCN_SHOP.index().equals(payOrder.getBusinessType())) {
                        BXSCNShopOrder bxscnShopOrder = orderCollect.getBxscnShopOrder();
                        bxscnShopOrder.setPayState(BXSCNShopOrderEnum.PayState.DepositSuccess.index());
                        bxscnShopOrder.setPayMoney(payOrder.getReceiptMoney());
                        bxscnShopOrder.setPayDate(payOrder.getPayDate());

                        if (BXSCNShopOrderService.self(bxscnShopOrder.getCreateDate()).paySuccess(bxscnShopOrder
                                ,orderCollect.getLogContent(),MemberWalletService.self(),operateInfo)) {
                            //添加会员订单
                            if (MemberBusinessOrderService.self(bxscnShopOrder.getCreateDate()).create(bxscnShopOrder) == null) {
                                log.error("充电宝订单创建会员订单失败，订单号：{{0}}", bxscnShopOrder.getTradeNo());
                            }
                            //触发业务订单创建事件
                            JFKafkaProducer producer = KafkaProducerFactory.self().getProducer();
                            if (producer != null) {
                                OrderCreateEvent event = new OrderCreateEvent(payOrder.getBusinessType(), bxscnShopOrder.getTradeNo(), bxscnShopOrder.getCreateDate());
                                KafkaMessage kafkaMessage = new KafkaMessage(KafkaEventConstants.TOPIC_Order,
                                        KafkaEventConstants.KEY_OrderCreate, JsonTools.toJson(event));
                                producer.send(kafkaMessage);
                            } else {
                                log.error("消息队列未初始化");
                            }
                        } else {
                            log.error("保存共享充电宝订单失败，缓存信息：{{0:json}}", orderCollect);
                        }
                    } else {
                        log.error("无效的支付订单业务类型，支付订单：{{0:json}}", payOrder);
                    }
                }else{
                    log.error("支付失败，支付信息：{{0:json}}",payOrder);
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        } else {
            //支付订单超时
            log.info("微信支付订单超时，回调信息：{{0:json}}", notify);

            BusyThreadPool.self().execute(new Runnable() {
                @Override
                public void run() {
                	WXPayAbnormalPayOrder timeoutPayOrder = null;
                    try {
                    	timeoutPayOrder = new WXPayAbnormalPayOrder();
                        timeoutPayOrder.setTradeNo(notify.getOut_trade_no());
                        timeoutPayOrder.setExternalTradeNo(notify.getTransaction_id());
                        timeoutPayOrder.setType(WXPayAbnormalPayOrderEnum.Type.Timeout.index());
                        timeoutPayOrder.setAppType(WXPayConfigEnum.AppType.wxxcx.index());
                        timeoutPayOrder.setAppId(notify.getAppid());
                        timeoutPayOrder.setPayerId(notify.getPayer().getOpenid());
                        timeoutPayOrder.setBusinessAccount(notify.getMchid());
                        timeoutPayOrder.setTradeType(notify.getTrade_type());
                        timeoutPayOrder.setPayMoney(notify.getAmount().getPayer_total());
                        timeoutPayOrder.setExternalContent(JsonTools.toJson(notify));
                        if (EWXPayNormalPayState.SUCCESS.name().equals(notify.getTrade_state())) {
                            timeoutPayOrder.setPayStatus(EPayState.Success.index());
                        } else {
                            timeoutPayOrder.setPayStatus(EPayState.Fail.index());
                        }
                        timeoutPayOrder.setCreateDate(new Date());
                        WXPayAbnormalPayOrderService.self().add(timeoutPayOrder);
                    } catch (Exception e) {
                    	log.error("微信支付订单超时入库失败，订单信息：{{0:json}}", timeoutPayOrder);
                    	log.error(e.getMessage(), e);
                    }
                }
            },3,TimeUnit.SECONDS);
        }
    }
    
    public static void payResult(final AlipayNormalPayNotify notify, OperateInfo operateInfo) {
        String json = null;
        CacheOrderCollect orderCollect = null;
        AlipayOrder payOrder = null;
        try {
            json = RedisTools.get().getAndRemove(RedisDBConstants.ORDER_CACHE_DB, notify.getTradeNo());
            if (StringTools.isNotBlank(json)) {
                orderCollect = JsonTools.fromJson(json, CacheOrderCollect.class);
                if (orderCollect != null) {
                    payOrder = orderCollect.getAlipayOrder();
                }
            }
        } catch (Exception e) {
            log.error("微信支付本系统缓存解析失败，微信回调：{{0:json}},缓存内容：{{1}}", notify, json);
            log.error(e.getMessage(), e);
        }

        if (payOrder != null) {
            try {
                int result = AlipayOrderService.self(payOrder.getCreateDate()).payResult(payOrder, notify);
                if (result == 1) {
                    if (EBusinessType.RECHARGE.index().equals(payOrder.getBusinessType())) {
                        MemberRechargeOrder rechargeOrder = orderCollect.getMemberRechargeOrder();
                        rechargeOrder.setPayState(payOrder.getPayStatus());
                        rechargeOrder.setPayMoney(payOrder.getReceiptMoney());
                        rechargeOrder.setPayDate(payOrder.getPayDate());
                        if (MemberRechargeOrderService.self(payOrder.getPayDate()).paySuccess(rechargeOrder, orderCollect.getLogContent(), operateInfo)) {
                            //触发业务订单创建事件
                            JFKafkaProducer producer = KafkaProducerFactory.self().getProducer();
                            if (producer != null) {
                                MemberRechargeFinishEvent event = new MemberRechargeFinishEvent(rechargeOrder.getTradeNo());
                                KafkaMessage kafkaMessage = new KafkaMessage(KafkaEventConstants.TOPIC_Order,
                                        KafkaEventConstants.KEY_MemberRechargeMoney, JsonTools.toJson(event));
                                producer.send(kafkaMessage);
                            } else {
                                log.error("消息队列未初始化");
                            }
                        }
                    } else if (EBusinessType.CDB.index().equals(payOrder.getBusinessType())) {
                        CDBOrder deviceOrder = orderCollect.getCdbOrder();
                        deviceOrder.setPayState(CDBOrderEnum.PayState.DepositSuccess.index());
                        deviceOrder.setPayMoney(payOrder.getReceiptMoney());
                        deviceOrder.setPayDate(payOrder.getPayDate());
                        ICDBNetworkService networkService = HttpNetworkServiceUtils.getCDBNetworkService(deviceOrder.getLeaseIotId());
                        if (CDBOrderService.self(deviceOrder.getCreateDate()).paySuccess(deviceOrder, orderCollect.getLogContent(), networkService, operateInfo)) {
                            //缓存工作中订单
                            RedisCacheManager.saveWorkingCDBDeviceOrder(deviceOrder);
                            //添加会员订单
                            if (MemberBusinessOrderService.self(deviceOrder.getCreateDate()).create(deviceOrder) == null) {
                                log.error("充电宝订单创建会员订单失败，订单号：{{0}}", deviceOrder.getTradeNo());
                            }
                            //触发业务订单创建事件
                            JFKafkaProducer producer = KafkaProducerFactory.self().getProducer();
                            if (producer != null) {
                                OrderCreateEvent event = new OrderCreateEvent(payOrder.getBusinessType(), deviceOrder.getTradeNo(), deviceOrder.getCreateDate());
                                KafkaMessage kafkaMessage = new KafkaMessage(KafkaEventConstants.TOPIC_Order,
                                        KafkaEventConstants.KEY_OrderCreate, JsonTools.toJson(event));
                                producer.send(kafkaMessage);
                            } else {
                                log.error("消息队列未初始化");
                            }
                        } else {
                            log.error("保存共享充电宝订单失败，缓存信息：{{0:json}}", orderCollect);
                        }
                    }else if (EBusinessType.PCL.index().equals(payOrder.getBusinessType())) {
                        PCLOrder deviceOrder = orderCollect.getPclOrder();
                        deviceOrder.setPayState(PCLOrderEnum.PayState.Success.index());
                        deviceOrder.setPayMoney(payOrder.getReceiptMoney());
                        deviceOrder.setPayDate(payOrder.getPayDate());
                        if (PCLOrderService.self(deviceOrder.getCreateDate()).paySuccess(deviceOrder, orderCollect.getLogContent(), operateInfo)) {
                            //缓存工作中订单
                            RedisCacheManager.saveWorkingPCLDeviceOrder(deviceOrder);
                            //添加会员订单
                            if (MemberBusinessOrderService.self(deviceOrder.getCreateDate()).create(deviceOrder) == null) {
                                log.error("充电宝订单创建会员订单失败，订单号：{{0}}", deviceOrder.getTradeNo());
                            }
                            //触发业务订单创建事件
                            JFKafkaProducer producer = KafkaProducerFactory.self().getProducer();
                            if (producer != null) {
                                OrderCreateEvent event = new OrderCreateEvent(payOrder.getBusinessType(), deviceOrder.getTradeNo(), deviceOrder.getCreateDate());
                                KafkaMessage kafkaMessage = new KafkaMessage(KafkaEventConstants.TOPIC_Order,
                                        KafkaEventConstants.KEY_OrderCreate, JsonTools.toJson(event));
                                producer.send(kafkaMessage);
                            } else {
                                log.error("消息队列未初始化");
                            }
                        } else {
                            log.error("保存共享充电宝订单失败，缓存信息：{{0:json}}", orderCollect);
                        }
                    }else if (EBusinessType.BXSCN.index().equals(payOrder.getBusinessType())) {
                        BXSCNOrder deviceOrder = orderCollect.getBxscnOrder();
                        deviceOrder.setPayState(CDBOrderEnum.PayState.DepositSuccess.index());
                        deviceOrder.setPayMoney(payOrder.getReceiptMoney());
                        deviceOrder.setPayDate(payOrder.getPayDate());
                        IBXSCNNetworkService networkService = HttpNetworkServiceUtils.getBXSCNNetworkService(deviceOrder.getLeaseIotId());
                        if (BXSCNOrderService.self(deviceOrder.getCreateDate()).paySuccess(deviceOrder, orderCollect.getLogContent(), networkService, operateInfo)) {
                            //缓存工作中订单
                            RedisCacheManager.saveWorkingBXSCNDeviceOrder(deviceOrder);
                            //添加会员订单
                            if (MemberBusinessOrderService.self(deviceOrder.getCreateDate()).create(deviceOrder) == null) {
                                log.error("便携式储能电池订单创建会员订单失败，订单号：{{0}}", deviceOrder.getTradeNo());
                            }
                            //触发业务订单创建事件
                            JFKafkaProducer producer = KafkaProducerFactory.self().getProducer();
                            if (producer != null) {
                                OrderCreateEvent event = new OrderCreateEvent(payOrder.getBusinessType(), deviceOrder.getTradeNo(), deviceOrder.getCreateDate());
                                KafkaMessage kafkaMessage = new KafkaMessage(KafkaEventConstants.TOPIC_Order,
                                        KafkaEventConstants.KEY_OrderCreate, JsonTools.toJson(event));
                                producer.send(kafkaMessage);
                            } else {
                                log.error("消息队列未初始化");
                            }
                        } else {
                            log.error("保存便携式储能电池租借订单失败，缓存信息：{{0:json}}", orderCollect);
                        }
                    } else if (EBusinessType.BXSCN_SHOP.index().equals(payOrder.getBusinessType())) {
                        BXSCNShopOrder bxscnShopOrder = orderCollect.getBxscnShopOrder();
                        bxscnShopOrder.setPayState(BXSCNShopOrderEnum.PayState.DepositSuccess.index());
                        bxscnShopOrder.setPayMoney(payOrder.getReceiptMoney());
                        bxscnShopOrder.setPayDate(payOrder.getPayDate());

                        if (BXSCNShopOrderService.self(bxscnShopOrder.getCreateDate()).paySuccess(bxscnShopOrder
                                ,orderCollect.getLogContent(),MemberWalletService.self(),operateInfo)) {
                            //添加会员订单
                            if (MemberBusinessOrderService.self(bxscnShopOrder.getCreateDate()).create(bxscnShopOrder) == null) {
                                log.error("充电宝订单创建会员订单失败，订单号：{{0}}", bxscnShopOrder.getTradeNo());
                            }
                            //触发业务订单创建事件
                            JFKafkaProducer producer = KafkaProducerFactory.self().getProducer();
                            if (producer != null) {
                                OrderCreateEvent event = new OrderCreateEvent(payOrder.getBusinessType(), bxscnShopOrder.getTradeNo(), bxscnShopOrder.getCreateDate());
                                KafkaMessage kafkaMessage = new KafkaMessage(KafkaEventConstants.TOPIC_Order,
                                        KafkaEventConstants.KEY_OrderCreate, JsonTools.toJson(event));
                                producer.send(kafkaMessage);
                            } else {
                                log.error("消息队列未初始化");
                            }
                        } else {
                            log.error("保存共享充电宝订单失败，缓存信息：{{0:json}}", orderCollect);
                        }
                    } else {
                        log.error("无效的支付订单业务类型，支付订单：{{0:json}}", payOrder);
                    }
                }else{
                    log.error("支付失败，支付信息：{{0:json}}",payOrder);
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        } else {
            //支付订单超时
            log.info("支付宝支付订单超时，回调信息：{{0:json}}", notify);
            
            BusyThreadPool.self().execute(new Runnable() {
                @Override
                public void run() {
                	AlipayAbnormalPayOrder timeoutPayOrder = null;
                    try {
                    	timeoutPayOrder = new AlipayAbnormalPayOrder();
                        timeoutPayOrder.setTradeNo(notify.getTradeNo());
                        timeoutPayOrder.setExternalTradeNo(notify.getExternalTradeNo());
                        timeoutPayOrder.setType(AlipayAbnormalPayOrderEnum.Type.Timeout.index());
                        timeoutPayOrder.setAppType(AlipayConfigEnum.AppType.alixcx.index());
                        timeoutPayOrder.setAppId(notify.getAppId());
                        timeoutPayOrder.setPayerId(notify.getPayerId());
                        timeoutPayOrder.setBusinessAccount(notify.getSellerId());
                        timeoutPayOrder.setTradeType(TradeType.Normal.name());
                        timeoutPayOrder.setPayMoney(notify.getMoney());
                        timeoutPayOrder.setExternalContent(notify.getJson());
                        if (EAliPayNormalTradeState.TRADE_SUCCESS.name().equals(notify.getTradeStatus())) {
                            timeoutPayOrder.setPayStatus(EPayState.Success.index());
                        } else {
                            timeoutPayOrder.setPayStatus(EPayState.Fail.index());
                        }
                        timeoutPayOrder.setCreateDate(new Date());
                        AlipayAbnormalPayOrderService.self().add(timeoutPayOrder);
                    } catch (Exception e) {
                    	log.error("支付宝支付订单超时入库失败，订单信息：{{0:json}}", timeoutPayOrder);
                    	log.error(e.getMessage(), e);
                    }
                }
            },3,TimeUnit.SECONDS);
        }
    }
    
    public static void payResult(final WXPayAdvancePayConfirmNotify notify, OperateInfo operateInfo) {
        String json = null;
        CacheOrderCollect orderCollect = null;
        WXPayOrder payOrder = null;
        try {
            json = RedisTools.get().getAndRemove(RedisDBConstants.ORDER_CACHE_DB, notify.getOut_order_no());
            if (StringTools.isNotBlank(json)) {
                orderCollect = JsonTools.fromJson(json, CacheOrderCollect.class);
                if (orderCollect != null) {
                    payOrder = orderCollect.getPayOrder();
                }
            }
        } catch (Exception e) {
            log.error("微信支付本系统缓存解析失败，微信回调：{{0:json}},缓存内容：{{1}}", notify, json);
            log.error(e.getMessage(), e);
        }

        if (payOrder != null) {
            try {
                int result = WXPayOrderService.self(payOrder.getCreateDate()).payResult(payOrder, notify);
                if (result == 1) {
                    if (EBusinessType.CDB.index().equals(payOrder.getBusinessType())) {
                        CDBOrder deviceOrder = orderCollect.getCdbOrder();
                        deviceOrder.setPayState(CDBOrderEnum.PayState.DepositSuccess.index());
                        deviceOrder.setPayMoney(payOrder.getReceiptMoney());
                        deviceOrder.setPayDate(payOrder.getPayDate());
                        ICDBNetworkService networkService = HttpNetworkServiceUtils.getCDBNetworkService(deviceOrder.getLeaseIotId());
                        if (CDBOrderService.self(deviceOrder.getCreateDate()).paySuccess(deviceOrder, orderCollect.getLogContent(), networkService, operateInfo)) {
                            //缓存工作中订单
                            RedisCacheManager.saveWorkingCDBDeviceOrder(deviceOrder);
                            //添加会员订单
                            if (MemberBusinessOrderService.self(deviceOrder.getCreateDate()).create(deviceOrder) == null) {
                                log.error("充电宝订单创建会员订单失败，订单号：{{0}}", deviceOrder.getTradeNo());
                            }
                            //触发业务订单创建事件
                            JFKafkaProducer producer = KafkaProducerFactory.self().getProducer();
                            if (producer != null) {
                                OrderCreateEvent event = new OrderCreateEvent(payOrder.getBusinessType(), deviceOrder.getTradeNo(), deviceOrder.getCreateDate());
                                KafkaMessage kafkaMessage = new KafkaMessage(KafkaEventConstants.TOPIC_Order,
                                        KafkaEventConstants.KEY_OrderCreate, JsonTools.toJson(event));
                                producer.send(kafkaMessage);
                            } else {
                                log.error("消息队列未初始化");
                            }
                        } else {
                            log.error("保存共享充电宝订单失败，缓存信息：{{0:json}}", orderCollect);
                        }
                    } else {
                        log.error("无效的支付订单业务类型，支付订单：{{0:json}}", payOrder);
                    }
                }else{
                    log.error("支付失败，支付信息：{{0:json}}",payOrder);
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        } else {
            //支付订单超时
            log.info("微信支付订单超时，回调信息：{{0:json}}", notify);

            BusyThreadPool.self().execute(new Runnable() {
                @Override
                public void run() {
                	WXPayAbnormalPayOrder timeoutPayOrder = null;
                    try {
                    	timeoutPayOrder = new WXPayAbnormalPayOrder();
                        timeoutPayOrder.setTradeNo(notify.getOut_order_no());
                        timeoutPayOrder.setExternalTradeNo(notify.getOrder_id());
                        timeoutPayOrder.setType(WXPayAbnormalPayOrderEnum.Type.Timeout.index());
                        timeoutPayOrder.setAppType(WXPayConfigEnum.AppType.wxxcx.index());
                        timeoutPayOrder.setAppId(notify.getAppid());
                        timeoutPayOrder.setPayerId(notify.getOpenid());
                        timeoutPayOrder.setBusinessAccount(notify.getMchid());
                        timeoutPayOrder.setTradeType(TradeType.PreAuthPay.name());
                        timeoutPayOrder.setPayMoney(notify.getTotal_amount());
                        timeoutPayOrder.setExternalContent(JsonTools.toJson(notify));
                        timeoutPayOrder.setPayStatus(EPayState.Close.index());
                        if (EWXPayAdvanceServerState.DOING.name().equals(notify.getState())) {
            				if(EWXPayAdvanceOrderState.USER_CONFIRM.name().equals(notify.getState_description())){
            					timeoutPayOrder.setPayStatus(EPayState.Confirm.index());
            				}
            			}
                        timeoutPayOrder.setCreateDate(new Date());
                        WXPayAbnormalPayOrderService.self().add(timeoutPayOrder);
                    } catch (Exception e) {
                    	log.error("微信支付订单超时入库失败，订单信息：{{0:json}}", timeoutPayOrder);
                    	log.error(e.getMessage(), e);
                    }
                }
            },3,TimeUnit.SECONDS);
        }
    }
    
    public static void payResult(final AlipayAdvancePayConfirmNotify notify, OperateInfo operateInfo) {
        String json = null;
        CacheOrderCollect orderCollect = null;
        AlipayOrder payOrder = null;
        try {
            json = RedisTools.get().getAndRemove(RedisDBConstants.ORDER_CACHE_DB, notify.getTradeNo());
            if (StringTools.isNotBlank(json)) {
                orderCollect = JsonTools.fromJson(json, CacheOrderCollect.class);
                if (orderCollect != null) {
                    payOrder = orderCollect.getAlipayOrder();
                }
            }
        } catch (Exception e) {
            log.error("支付宝预支付本系统缓存解析失败，微信回调：{{0:json}},缓存内容：{{1}}", notify, json);
            log.error(e.getMessage(), e);
        }

        if (payOrder != null) {
            try {
                int result = AlipayOrderService.self(payOrder.getCreateDate()).payResult(payOrder, notify);
                if (result == 1) {
                    if (EBusinessType.CDB.index().equals(payOrder.getBusinessType())) {
                        CDBOrder deviceOrder = orderCollect.getCdbOrder();
                        deviceOrder.setPayState(CDBOrderEnum.PayState.DepositSuccess.index());
                        deviceOrder.setPayMoney(payOrder.getReceiptMoney());
                        deviceOrder.setPayDate(payOrder.getPayDate());
                        ICDBNetworkService networkService = HttpNetworkServiceUtils.getCDBNetworkService(deviceOrder.getLeaseIotId());
                        if (CDBOrderService.self(deviceOrder.getCreateDate()).paySuccess(deviceOrder, orderCollect.getLogContent(), networkService, operateInfo)) {
                            //缓存工作中订单
                            RedisCacheManager.saveWorkingCDBDeviceOrder(deviceOrder);
                            //添加会员订单
                            if (MemberBusinessOrderService.self(deviceOrder.getCreateDate()).create(deviceOrder) == null) {
                                log.error("充电宝订单创建会员订单失败，订单号：{{0}}", deviceOrder.getTradeNo());
                            }
                            //触发业务订单创建事件
                            JFKafkaProducer producer = KafkaProducerFactory.self().getProducer();
                            if (producer != null) {
                                OrderCreateEvent event = new OrderCreateEvent(payOrder.getBusinessType(), deviceOrder.getTradeNo(), deviceOrder.getCreateDate());
                                KafkaMessage kafkaMessage = new KafkaMessage(KafkaEventConstants.TOPIC_Order,
                                        KafkaEventConstants.KEY_OrderCreate, JsonTools.toJson(event));
                                producer.send(kafkaMessage);
                            } else {
                                log.error("消息队列未初始化");
                            }
                        } else {
                            log.error("保存共享充电宝订单失败，缓存信息：{{0:json}}", orderCollect);
                        }
                    } else {
                        log.error("无效的支付订单业务类型，支付订单：{{0:json}}", payOrder);
                    }
                }else{
                    log.error("支付失败，支付信息：{{0:json}}",payOrder);
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        } else {
            //支付订单超时
            log.info("支付宝支付订单超时，回调信息：{{0:json}}", notify);

            BusyThreadPool.self().execute(new Runnable() {
                @Override
                public void run() {
                	AlipayAbnormalPayOrder timeoutPayOrder = null;
                    try {
                    	timeoutPayOrder = new AlipayAbnormalPayOrder();
                        timeoutPayOrder.setTradeNo(notify.getTradeNo());
                        timeoutPayOrder.setExternalTradeNo(notify.getExternalTradeNo());
                        timeoutPayOrder.setType(AlipayAbnormalPayOrderEnum.Type.Timeout.index());
                        timeoutPayOrder.setAppType(AlipayConfigEnum.AppType.alixcx.index());
                        timeoutPayOrder.setAppId(notify.getAppId());
                        timeoutPayOrder.setPayerId(notify.getPayerId());
                        //timeoutPayOrder.setBusinessAccount(notify.getSellerId());
                        timeoutPayOrder.setTradeType(TradeType.Normal.name());
                        timeoutPayOrder.setPayMoney(notify.getMoney());
                        timeoutPayOrder.setExternalContent(notify.getJson());
                        timeoutPayOrder.setPayStatus(EPayState.Close.index());
                        if (EAlipayAdvanceOrderState.AUTHORIZED.name().equals(notify.getStatus())) {
            				timeoutPayOrder.setPayStatus(EPayState.Confirm.index());
            			}else if(EAlipayAdvanceOrderState.FINISH.name().equals(notify.getStatus())) {
            				timeoutPayOrder.setPayStatus(EPayState.Success.index());
            			}
                        timeoutPayOrder.setCreateDate(new Date());
                        
                        AlipayAbnormalPayOrderService.self().add(timeoutPayOrder);
                    } catch (Exception e) {
                    	log.error("支付宝支付订单超时入库失败，订单信息：{{0:json}}", timeoutPayOrder);
                    	log.error(e.getMessage(), e);
                    }
                }
            },3,TimeUnit.SECONDS);
        }
    }
    
    public static void payResult(final WXPayAdvancePayFinishNotify notify, OperateInfo operateInfo) {
    	//TODO 这里需要考虑跨年处理
    	WXPayOrder payOrder = WXPayOrderService.self(new Date()).getByTradeNo(notify.getOut_order_no());
		if(payOrder == null){
			payOrder = WXPayOrderService.self(new Date()).getByExternalTradeNo(notify.getOrder_id());
		}
        if (payOrder != null) {
            try {
                int result = WXPayOrderService.self(payOrder.getCreateDate()).payResult(payOrder, notify);
                if (result == 1) {
                    if (EBusinessType.CDB.index().equals(payOrder.getBusinessType())) {
                        CDBOrder deviceOrder = CDBOrderService.self(payOrder.getCreateDate()).getByTradeNo(payOrder.getBusinessTradeNo());
                        if (CDBOrderService.self(deviceOrder.getCreateDate()).advancePayfinish(deviceOrder,payOrder, operateInfo)) {
                        	//移除缓存
                            RedisCacheManager.removeWorkingCDBDeviceOrder(deviceOrder.getTradeNo());
                            //添加会员订单
                            if (MemberBusinessOrderService.self(deviceOrder.getCreateDate()).finish(deviceOrder.getTradeNo(),deviceOrder.getMoney()
                        			,deviceOrder.getPayMoney(), deviceOrder.getWalletMoney())) {
                                log.error("充电宝订单更新会员订单失败，订单号：{{0}}", deviceOrder.getTradeNo());
                            }
                            //触发业务订单创建事件
                            JFKafkaProducer producer = KafkaProducerFactory.self().getProducer();
                            if (producer != null) {
                            	OperateInfo temp = ClassTools.copy(new OperateInfo(), operateInfo);
								OrderFinishEvent event = new OrderFinishEvent(EBusinessType.CDB.index(), deviceOrder.getTradeNo(), new Date(), temp);
								KafkaMessage kafkaMessage = new KafkaMessage(KafkaEventConstants.TOPIC_Order, KafkaEventConstants.KEY_OrderFinish, JsonTools.toJson(event));
								producer.send(kafkaMessage);
                            } else {
                                log.error("消息队列未初始化");
                            }
                        } else {
                            log.error("修改共享充电宝订单失败，设备订单信息：{{0:json}}", deviceOrder);
                        }
                    } else {
                        log.error("无效的支付订单业务类型，支付订单：{{0:json}}", payOrder);
                    }
                }else{
                    log.error("支付失败，支付信息：{{0:json}}",payOrder);
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        } else {
            //支付订单超时
            log.info("微信支付订单超时，回调信息：{{0:json}}", notify);
            
            BusyThreadPool.self().execute(new Runnable() {
                @Override
                public void run() {
                	WXPayAbnormalPayOrder timeoutPayOrder = null;
                    try {
                    	timeoutPayOrder = new WXPayAbnormalPayOrder();
                        timeoutPayOrder.setTradeNo(notify.getOut_order_no());
                        timeoutPayOrder.setExternalTradeNo(notify.getOrder_id());
                        timeoutPayOrder.setType(WXPayAbnormalPayOrderEnum.Type.Timeout.index());
                        timeoutPayOrder.setAppType(WXPayConfigEnum.AppType.wxxcx.index());
                        timeoutPayOrder.setAppId(notify.getAppid());
                        timeoutPayOrder.setPayerId(notify.getOpenid());
                        timeoutPayOrder.setBusinessAccount(notify.getMchid());
                        timeoutPayOrder.setTradeType(TradeType.PreAuthPay.name());
                        timeoutPayOrder.setPayMoney(notify.getTotal_amount());
                        timeoutPayOrder.setExternalContent(JsonTools.toJson(notify));
                        if (EWXPayAdvanceServerState.REVOKED.name().equals(notify.getState()) 
                        		|| EWXPayAdvanceServerState.EXPIRED.name().equals(notify.getState())) {
                            timeoutPayOrder.setPayStatus(EPayState.Fail.index());
                        } else {
                            timeoutPayOrder.setPayStatus(EPayState.Success.index());
                        }
                        timeoutPayOrder.setCreateDate(new Date());
                        WXPayAbnormalPayOrderService.self().add(timeoutPayOrder);
                    } catch (Exception e) {
                    	log.error("微信支付订单超时入库失败，订单信息：{{0:json}}", timeoutPayOrder);
                    	log.error(e.getMessage(), e);
                    }
                }
            },3,TimeUnit.SECONDS);
        }
    }

    public static CacheOrderCollect getCacheOrderCollect(String tradeNo){
        CacheOrderCollect orderCollect = null;
        try {
            String json = RedisTools.get().get(RedisDBConstants.ORDER_CACHE_DB, tradeNo);
            if (StringTools.isNotBlank(json)) {
                orderCollect = JsonTools.fromJson(json, CacheOrderCollect.class);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return orderCollect;
    }
}
